Junit测试新思路
先来看看之前使用的原生Junit测试,我们已经很熟悉了:
@Test
// 测试数据源连接
public void test1() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource dataSource = (ComboPooledDataSource) app.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
@Test
// 测试userService对象
public void test2() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) app.getBean("userService");
System.out.println(userService);
}
这样的设计似乎不是那么完美:
① 每次都要new
出app容器
② 再使用getBean
获取到被测试的对象
因此,我们想到的一种更加优美的设计:通过注解,直接给测试类注入想要测试的Bean对象。
Spring集成Junit实现思路
❶ 导入Junit坐标
❷ 使用 @RunWith 标明该类运行于spring测试环境
❸ 使用 @ContextConfiguration 指定配置文件/配置类
❹ 使用 @Autowired 注入想要测试的对象
❺ 使用 @Test 进行测试,一般打印对象即可
代码演示
❶ 导入Junit坐标
<!-- 注意:如果spring是5版本及以上,junit版本必须是4.12及以上 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
❷❸❹❺ 测试类代码设计
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml") // 如果是配置文件
@ContextConfiguration(classes = {
SpringConfiguration.class}) // 如果是配置类
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test() {
System.out.println(userService);
System.out.println(dataSource);
}
}