繁体   English   中英

如何手动在 Spring Boot 中引导测试(没有 @SpringBootTest-Annotation)

[英]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):

  1. 添加/注入一些模拟作为服务(手动添加绑定到 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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM