Spring整合Junit
# 60.Spring整合Junit
我们在介绍Spring的时候说过,Spring整合了很多流行的框架,那么当然也包括Junit
# 目前项目存在的问题
我们目前的测试类中,其实是有很多重复代码的,每个方法都包含了创建容器,获取对象的代码。用我们之前的知识来解决的话,可以使用@Before注解:
public class AccountServiceTest {
private ApplicationContext ac ;
private IAccountService as;
@Before
public void init() {
ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
as = ac.getBean("accountService", IAccountService.class);
}
@Test
public void testFindAll() {
ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
ac.getBean("accountService", IAccountService.class);
List<Account> allAccount = as.findAllAccount();
for (Account account : allAccount) {
System.out.println(account);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
在实际开发过程中,开发人员和测试人员可能不是同一人!也就是说,让测试人员去编写初始化的方法,是比较困难的,因为他可能不懂我们的代码,只关心测试结果。
那么怎么解决呢?我们来分析下:
- 应用程序的入口:main方法
- Junit单元测试中,没有main方法也能执行,这是因为Junit集成了一个main方法,该方法就会判断当前测试类中哪些方法有 @Test注解,Junit就让有Test注解的方法执行
- Junit不会管我们是否采用 Spring 框架,在执行测试方法时,Junit根本不知道我们是不是使用了Spring框架,所以也就不会为我们读取配置文件/配置类创建spring核心容器
- 由以上三点可知,当测试方法执行时,没有IoC容器,就算写了Autowired注解,也无法实现注入
为此,我们需要使用Spring提供的整合Junit的依赖,替代Junit中默认的main方法,使其可创建IoC容器。
# Spring整合Junit
整合步骤:
导入 Spring 整合 Junit 的 依赖
使用Junit提供的一个注解,把原有的main方法替换了,替换成 Spring 提供的 @Runwith注解,它会读取配置文件或者注解,创建容器。
使用@ContextConfiguration注解,告知 Spring 注解或XML文件的配置。取值有:
locations:指定xml文件的位置,需加上classpath关键字,表示在类路径下。
classes:指定注解类所在地位置 ,需加上classpath关键字,表示在类路径下。
例如:
@ContextConfiguration(classes = SpringConfiguration.class)
@ContextConfiguration(locations = "classpath:bean.xml")
1
2
2
接下来我们开始整合。
# 导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
1
2
3
4
5
2
3
4
5
注意,spring-test 的版本最好和 spring一致
同时,当我们使用Spring 5.x版本的时候,要求 Junit 必须是4.12及以上,否则会报错:
Caused by: java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher.
1
# 使用spring-test的注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private ApplicationContext ac ;
@Autowired
private IAccountService as;
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
此时,测试方法就可以正常运行了。
# 源码
本项目已将源码上传到GitHub (opens new window)和Gitee (opens new window)上。并且创建了分支demo8,读者可以通过切换分支来查看本文的示例代码。
在GitHub上编辑此页 (opens new window)
上次更新: 2023/5/11 14:10:59