Spring - 07集成Junit
(1)原始Junit测试Spring问题
在测试类中,每个测试方法都有以下两行代码:
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = app.getBean(DataSource.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常,所以不能轻易删除。
(2)解决思路
- 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它。
- 将需要进行测试的Bean直接在测试类中进行注入。
(3)测试
(3.1)导入Spring集成Junit的坐标
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.9.RELEASE</version> </dependency>
(3.2)更换注解
- 使用@RunWith注解替换原来的运行器;
- 使用@ContextConfiguration指定配置文件或配置类;
- 使用@Autowired注入需要测试的对象
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfiguration.class}) // @ContextConfiguration("classpath:applicationContext.xml") public class SpringJunitTest { @Autowired private UserService userService; @Autowired private DataSource dataSource; @Test public void test1() throws Exception { System.out.println(dataSource.getConnection()); userService.save(); }
}