spring boot的单元测试跟spring的单元测试相比,稍微有一些改变。
pom.xml需要引用:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency>
抽象测试类:
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! @SpringApplicationConfiguration(classes = App.class) // 指定我们SpringBoot工程的Application启动类 @WebAppConfiguration public abstract class SpringTxTestCase extends AbstractTransactionalJUnit4SpringContextTests { protected DataSource dataSource; protected JdbcTemplate jdbcTemplate; @Override @Autowired public void setDataSource(DataSource dataSource) { super.setDataSource(dataSource); this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(dataSource); }
}
测试类只要继承SpringTxTestCase 类,就可以进行单元测试了。
源码地址:https://github.com/jinjunzhu/spring-boot-jdbc.git
