在之前的测试方法中,几乎都能看到以下的两行代码:
ApplicationContext context = new classPathXmlApplicationContext("xxx.xm");
XXXX XXX = context.getBean(Xxxx.cTass);
这两行代码的作用是创建Spring容器,最终获取到对象,但是每次测试都需要重复编写。
针对上述问题,我们需要的是程序能自动帮我们创建容器。我们都知道JUnit无法知晓我们是否使用了 Spring 框架,更不用说帮我们创建Spring 容器了。
Spring提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件位置就可以了。这样就能通过Spring整合JUnit可以使程序创建spring容器了
整合Junit5
1.引入相关依赖
java
<!-- spring整合Junit相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>6.0.2</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
2.创建实体类
java
@Component
public class User {
public void run(){
System.out.println("user...");
}
}
3.配置bean.xml文件
java
<?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.yogurt.spring6.junit"></context:component-scan>
</beans>
4.测试
java
@SpringJUnitConfig(locations = "classpath:bean.xml")
public class SpringTestJunit5 {
//注入
@Autowired
private User user;
//测试
@Test
public void testUser(){
System.out.println(user);
user.run();
}
}
注:@SpringJUnitConfig(locations = "classpath:bean.xml")可以替换成
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean.xml")
整合Junit4
1.引入相关依赖
java
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
2.创建实体类
java
@Component
public class User {
public void run(){
System.out.println("user...");
}
}
3.配置bean.xml文件
java
<?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.yogurt.spring6.junit"></context:component-scan>
</beans>
4.测试
java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class SpringTestJunit4 {
@Autowired
private User user;
@Test
public void testUser(){
System.out.println(user);
user.run();
}
}