![](/img/trans.png)
[英]Where can I find the Javadoc for Spring Boot Annotation @SpringBootTest (ie, for Package org.springframework.boot.test.context)?
[英]How to bootstrap a test in Spring Boot manually (without @SpringBootTest-Annotation)
我正在将一个项目从Play Framework迁移到带有Web Flux 的Spring Boot,并在我手动启动它时基本运行。 但是,我的大部分测试还没有工作。 (我的play.Application
显然不能注入org.springframework.beans.factory.BeanFactory
因为没有绑定实现。)使用 Play Framework 我曾经在我的测试中创建一个应用程序:
play.Application app = new play.inject.guice.GuiceApplicationBuilder()
.bindings(
// here I added a few manual bindings (e.g. mocks)
).build();
// Then I could get "beans" out of it:
MyFancyService fancyService = app.injector().instanceOf(MyFancyService.class);
// Or send Http-Requests to it:
Result response = route(app, request);
如何使用 Spring Boot 做到这一点?
我试过/考虑过:
@SpringBootTest(SpringBootTest.WebEnvironment.MOCK)
或@WebFluxTest
注释我的所有测试,并添加一个@Autowired WebTestClient webClient
。 然而,尤其是在迁移过程中,我不想过多地更改我的所有测试(上面的代码目前仅在org.junit.Rule
中的一个地方)。new SpringBootTestContextBootstrapper().buildTestContext().getApplicationContext()
创建ApplicationContext
,但无法弄清楚如何向它发送请求。基本上我正在寻找 Spring Boot 中的这三个关键特性(如果可能,使用 Web Flux):
app.getInstanceOf(MyFancyService.class)
)最后我或多或少地想通了:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class WithApp extends ExternalResource {
private final WebTestClient webTestClient;
public WithApp() {
SpringBootTestContextBootstrapper springBootTestContextBootstrapper = new SpringBootTestContextBootstrapper();
springBootTestContextBootstrapper.setBootstrapContext(new DefaultBootstrapContext(WithApp.class, new DefaultCacheAwareContextLoaderDelegate()));
MergedContextConfiguration config = springBootTestContextBootstrapper.buildMergedContextConfiguration();
ApplicationContext app = new ApplicationContextLoader().loadContext(config);
MyBean mockedBean = app.getBean(MyBean.class);
this.webTestClient = WebTestClient.bindToApplicationContext(app).build();
}
public WebTestClient.ResponseSpec call(HttpMethod method, String uri, Object body) {
return webTestClient.method(method).uri(uri).bodyValue(body).exchange();
}
@Component
public static class Config {
@Primary
@Bean
public MyBean getMyBeanForTest() {
return mock(MyBean.class);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.