【问题标题】:Junit with spring boot application [closed]带有 Spring Boot 应用程序的 Junit [关闭]
【发布时间】:2016-06-13 10:40:01
【问题描述】:

我有一个设计了 spring boot 和 hibernate 的应用程序。现在我想使用 Junit 进行单元测试。 application.properties 中应该包含什么,我们是否需要一个单独的 Java 文件进行测试?任何可以帮助我入门的工作示例或文档

【问题讨论】:

    标签: hibernate junit spring-boot


    【解决方案1】:

    包含以下依赖项,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
        }    
    }
    

    【讨论】:

    • 当我将 DataLayerTest 作为一个类包含时的测试报告:Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.053 sec &lt;&lt;&lt; FAILURE! - in org.test.DataLayerTest testFindall(org.test.DataLayerTest) Time elapsed: 0.047 sec &lt;&lt;&lt; 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]
    • 好吧,我假设您在服务/数据层中使用 Spring 事务管理。在这一点上,如果不知道任何进一步的细节,就很难确定这是错误的。请参阅 Spring 参考资料docs.spring.io/spring/docs/current/spring-framework-reference/…
    猜你喜欢
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 2020-09-22
    • 2019-03-22
    • 2021-10-28
    • 2015-12-24
    • 2017-03-05
    • 2018-07-22
    相关资源
    最近更新 更多