0.为什么要在Spring中进行单元测试?
如果没有单元测试,我们测试代码时不仅必须要写在main方法
而且每次都要去写代码获取ApplicationContext对象并用getBean()方法拿到其他对象
而使用单元测试就可以随时随地测代码,只需要加上相应的注解并直接在那注入对象即可
1. 导入spring-test坐标
除了创建Spring项目必须导入的spring-context坐标外
还要导入spring-test坐标极其依赖的junit坐标
注意spring-context坐标和spring-test坐标的版本要一致!
2.用@Runwith注解替换原来的运行期
在需要的测试类上加上@RunWith(SpringJUnit4ClassRunner.class)注解
3.用@ContextConfiguration配置注解文件或配置类
4.用Autowired注入需要测试的对象
5.编写测试方法并在方法上加上@Test注解
下面时一段测试代码写法的演示:
@RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration("classpath:application-context.xml") 如果有配置文件就用这个
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void test(){
userService.save();
}
@Autowired
private DataSource dataSource;
@Test
public void testDataSource() throws SQLException {
System.out.println("==========测试数据源的连接对象===========");
System.out.println(dataSource.getConnection());
}
}
常见报错:org.junit.runners.model.InvalidTestClassError: Invalid test class ‘com.lxl.test.JdbcTemplateCRUDTest’: 1. No runnable methods
这里是有一个大坑,在写@Test注解时稍不注意就会出错,因为有两个同名的@Test注解
如果引入错了一个的话,就会出错,在Spring集成Junit进行单元测试的时候,一定要选org.junit.Test的!!!