在开始之前我们先想下为什么我们spring要整合Junit单元测试
1、应用程序的入口
main
2、junit单元测试中没有main方法也可以执行
junit集成了一个main方法
该方法就会判断当前测试类中哪些方法有@Test注解
3、junit不会管我们是否采用spring框架
在执行测试方法时,junit根本不知道我们是不是使用了spring框架
所以也就不会为我们读取配置文件/配置类创建spring核心容器
由以上三点可知:当测试方法执行时,没有IOC容器,就算写了@Autowired注解,也无法实现注入
Spring整合Junit配置
1、导入spring整合junit的jar(坐标)
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
注意点:当我们使用spring5.x版本的时候,要求junit的jar必须是4.12及其以上
2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
@RunWith(SpringJUnit4ClassRunner.class)
3、告知spring的运行器、spring和ioc创建是基于xml还是注解的,并且说明位置。
@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注解类所在地位置
注解方式整合
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
//private AnnotationConfigApplicationContext ac;
@Autowired
private IAccountService as;
@Test
public void testFindAll() {
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
}
配置文件方式整合
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
//private AnnotationConfigApplicationContext ac;
@Autowired
private IAccountService as;
@Test
public void testFindAll() {
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
}