先看之前我们之前的测试类:
我们想去测试spring为我们创建的对象,我们需要加载配置文件去创建spring容器,然后根据Spring中的getBean方法去获取Bean的实例。
这样测试起来会特别麻烦,所以开发者将junit整合到Spring框架中,来简化这些操作,让开发者可以直接在测试类注入Bean实例,前提是把配置文件的名称或者配置类告诉spring!!
在pom文件导入spring-test的jar包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
在测试类中加入注解
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestAccount {
@Autowired
private AccountService accountService;
@Test
public void test01(){
try {
System.out.println(accountService.findAll());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
crtl+H查看SpringRunner的类结构如下
可以看出junit测试封装的有runner类,而SpringRunner是我们导入的spring-test包下的类,首先他继承junit下的runner类,处理提供junit的功能并且可以通过注解的方法读取外部文件,这样就可以对applicationContext.xml配置文件进行读取,为accountService进行依赖注入。