【发布时间】:2016-06-13 10:40:01
【问题描述】:
我有一个设计了 spring boot 和 hibernate 的应用程序。现在我想使用 Junit 进行单元测试。 application.properties 中应该包含什么,我们是否需要一个单独的 Java 文件进行测试?任何可以帮助我入门的工作示例或文档
【问题讨论】:
标签: hibernate junit spring-boot
我有一个设计了 spring boot 和 hibernate 的应用程序。现在我想使用 Junit 进行单元测试。 application.properties 中应该包含什么,我们是否需要一个单独的 Java 文件进行测试?任何可以帮助我入门的工作示例或文档
【问题讨论】:
标签: hibernate junit spring-boot
包含以下依赖项,spring boot 将自行配置以进行测试。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
之后,您应该能够从 src/test/java 运行测试。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class ApplicationTests {
@Test
public void contextLoads() {
}
}
对于数据层测试,在方法或类上使用 @Transactional。您可以通过扩展主测试类来创建一个单独的测试类。更多选项见下文
@Transactional
public class DataLayerTest extends ApplicationTests{
@Autowired
private LeaveDaoImpl daoImpl;
@Test
// @Transactional
// @Rollback(true)
public void testFindall() {
// you test here
}
}
【讨论】:
Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.053 sec <<< FAILURE! - in org.test.DataLayerTest testFindall(org.test.DataLayerTest) Time elapsed: 0.047 sec <<< ERROR! java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional test for test context [DefaultTestContext@8e24743 testClass = DataLayerTest, testInstance = org.test.DataLayerTest@39d76cb5, testMethod = testFindall@DataLayerTest, testException = [null]