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