往期文章:
Spring 学习总结笔记【一、快速入门】
Spring 学习总结笔记【二、IoC-控制反转】
Spring 学习总结笔记【三、注解开发】
一、前言
在前面篇章提到的Spring的测试类中,每个测试方法都有以下两行代码:
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = app.getBean("bookDao", BookDao.class);
这两行代码作用是获取容器,如果省略不写,会出现空指针异常。所以又不能轻易删除。
二、解决思路
- 使用SpringJunit创建Spring容器,但是需要将配置文件名称告诉它。
- 将需要进行测试的Bean直接在测试类中进行注入。
三、整合Junit开发步骤
① 导入Spring集成Junit的坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
② 使用@Runwith注解替换原来的运行期
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}
③ 使用@ContextConfiguration指定配置文件或配置类
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = SpringConfig.class)
public class SpringJunitTest {
}
④ 使用@Autowired注入需要测试的对象
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(value = {"classpath:applicationContext.xml"})
@ContextConfiguration(classes = {SpringConfig.class})
public class SpringJunitTest {
@Autowired
private BookService bookService;
// 测试查询
@Test
public void test1(){
bookService.save();
}
}
下期文章