Spring 集成 Junit
3.1 原始 Junit 测试 Spring 的问题
在测试类中,每个测试方法都有以下两种代码:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService bean = applicationContext.getBean(UserService.class);
不写会提示空指针,不能轻易删除。而每次测试还要编写这两行代码,比较繁琐。
3.2 上述问题解决思路
- 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它
- 将需要进行测试Bean直接在测试类中进行注入
3.3 Spring 集成 Junit 步骤
- 导入spring继承Junit的坐标
- 使用@Runwith注解替换原来的运行期
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
步骤实现:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void test1(){
userService.save();
}
}