提问者:小点点

单独分级子项目中的测试Spring等级


我的项目被分成几个gradle子项目(模块)。我有一个模块,其中包含几个Spring组件/bean。我想使用jUnit、mockito和springboottest测试这些bean,并具有autowled和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 {
}

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


共1个答案

匿名用户

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

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

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