一、sping6整合junit5
2、 实际作用
简化以下两行代码,通过注解方式获取bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beanaop.xml"); InterfaceTool bean = context.getBean(InterfaceTool.class);
3、配置基本的xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启组件扫描--> <context:component-scan base-package="com.ruqi.junit5test"></context:component-scan> </beans>
4、代码举例
package com.ruqi.junit5test.junit5;
import org.springframework.stereotype.Component;
@Component
public class User {
public void run(){
System.out.println("用于测试");
}
}
=====================================
package com.ruqi.junit5test.junit5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* 第二种方式,了解即可
* @ExtendWith(SpringExtension.class)
* @ContextConfiguration("classpath:bean.xml")
*/
@SpringJUnitConfig(locations = "classpath:bean.xml") //添加xml的配置即可自动获取bean对象
public class SpringJunit5 {
@Autowired
private User user;
@Test
public void testJunit5(){
user.run();
}
}
二、sping6整合junit4
1、引入依赖,见首行配置
2、例子如下
package com.ruqi.junit5test.junit4;
import com.ruqi.junit5test.junit5.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class SpringJunit4 {
@Autowired
private User user;
@Test
public void testJunit4(){
user.run();
}
}
版权声明:本文为qq_34577961原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。