【问题标题】:Test spring classes in separate gradle subproject在单独的 gradle 子项目中测试 spring 类
【发布时间】:2017-01-09 09:28:00
【问题描述】:

我的项目分为几个 gradle 子项目(模块)。我有一个包含几个弹簧组件/bean 的模块。我想使用 junit、mockito 和 springboottest 测试这些 bean,这些 bean 具有 autowired 和 mockbean 等功能。我正在使用

@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest

注释,但是当我尝试运行测试时,我得到了

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

这是因为该模块中没有主类(@SpringBootApplication)。

可以通过创建类似的模拟主类来避免这种情况

@SpringBootApplication
class TestApp {
}

有没有办法让它在不创建模拟主类的情况下工作?

【问题讨论】:

    标签: spring unit-testing testing spring-boot


    【解决方案1】:

    如果你想在子模块中运行测试,你需要定义一些配置类。可以是@Configuration@ComponentScan位于子模块的src/test/java根包中,这样就不会污染你的生产代码了。

    有了这样的测试配置,只需使用@SpringBootTest(classes=YourTestConfiguration.class)

    也许您想查看自 Spring Boot 1.4.x 以来称为 @TestConfiguration 的新注解。那是专门为仅测试配置量身定制的。

    【讨论】:

    • 看起来和创建mock主类一样(也可以位于src/test/java中)。
    • 如果没有一些 @Configuration(从 @SpringBootApplication 扩展),您将无法使用 Spring Context 运行任何测试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多