我有一个使用 SpringBoot 创建的自定义库(启动器)。因此,它没有 main 方法或 @SpringBootApplication
带注释的类。
我想使用 JUnit 测试这个入门功能。我在 src/test
(TestApplication
) 中创建了一个类作为启动器。
@SpringBootTest
@ContextConfiguration(classes = TestApplication.class)
@RunWith(SpringRunner.class)
public class SettingsTest {
@Autowired
private MyService myService;
@Test
public void testSettingsLoad(){
//do smth
}
}
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
但是,TestApplication
main
未调用,并且应用程序上下文未正确引发。
我尝试过不使用 @RunWith
注释(根本没有 Spring 上下文),并直接将类添加到 @SpringBootTest
注释(也被忽略)。
我已阅读 this post , 但这并没有多大帮助。
任何想法表示赞赏。
最佳答案
启动器是自动配置。当我编写启动器时,我不会测试使用启动器的 spring-boot 应用程序,而是测试启动器本身,这在 49.4 Testing your Auto-configuration 部分中有很好的记录。
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(UserServiceAutoConfiguration.class));
@Test
public void defaultServiceBacksOff() {
this.contextRunner.withUserConfiguration(UserConfiguration.class)
.run((context) -> {
assertThat(context).hasSingleBean(UserService.class);
assertThat(context.getBean(UserService.class))
.isSameAs(context.getBean(UserConfiguration.class).myUserService());
});
}
因此,您要做的就是创建一个 ApplicationRunnerContext,然后从启动器中加载您的入口类,然后在该上下文中断言已加载的内容。
关于java - 使用 Springboot+JUnit 测试启动器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689106/