gpt4 book ai didi

java - 如何在 Spring Boot 中手动引导测试(不使用 @SpringBootTest-Annotation)

转载 作者:行者123 更新时间:2023-12-01 19:04:03 24 4
gpt4 key购买 nike

我正在从 Play Framework 迁移项目使用 Web Flux 到 Spring Boot当我手动启动它时它基本上运行了。然而,我的大部分测试还没有发挥作用。 (我的 play.Application 显然无法注入(inject) org.springframework.beans.factory.BeanFactory 因为没有绑定(bind)实现。)使用 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):

  1. 添加/注入(inject)一些模拟作为服务(手动添加绑定(bind)到 BeanFactory)
  2. 访问一些自动设置的服务(例如 app.getInstanceOf(MyFancyService.class))
  3. 发送 Http 请求

最佳答案

最后我或多或少弄清楚了:

@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);
}
}
}

关于java - 如何在 Spring Boot 中手动引导测试(不使用 @SpringBootTest-Annotation),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com