gpt4 book ai didi

java - 如何在 Junit 5 *before* Spring 测试上下文加载之前获得回调?

转载 作者:行者123 更新时间:2023-12-03 18:59:31 25 4
gpt4 key购买 nike

在运行任何测试之前,我正在使用 Junit 5 扩展来启动 Wiremock 服务器。但是,Spring 上下文中的一个 bean 将远程调用作为其初始化的一部分,我无法更改,并且该调用会导致 ConnectionException,因为 Wiremock 服务器尚未启动。
如何在 Spring 加载文本上下文之前配置 JUnit 5 测试以获取回调?
我的 JUnit 5 扩展如下所示:

public class MyWiremockExtension implements BeforeAllCallback, AfterAllCallback {

private final WireMockServer wireMock = new WireMockServer(...);

@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
wireMock.start();
}

@Override
public void afterAll(ExtensionContext extensionContext) throws Exception {
wireMock.stop();
}
}
Spring Bean 配置深埋在我的 OkHttpClient bean 所依赖的上游代码中,但它看起来像这样:
@Configuration
public class OkHttpClientConfiguration {

@Bean
OkHttpClient okHttpClient(...) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()...build();
// wrap the okHttpClient in OAuth handling code which eagerly fetches a token
}
}
我的测试是这样的:
@SpringBootTest(properties = {...})
@ExtendWith(MyWiremockExtension.class)
class MyTest {
...
}
到目前为止,我找到的最接近的答案是 How to register Spring Context Events for current test ApplicationContext at runtime ,但在测试上下文加载之前不提供回调方法。
我对如何做到这一点的最佳猜测是:
  • 创建我自己的 ContextCustomizerFactory , 或
  • 延长 SpringBootTestContextBootstrapper , 覆盖 buildTestContext()在调用之前启动线模拟 super.buildTestContext() ,然后 @BootstrapWith我的类(class)而不是 Spring Boot 的类(class),但我不确定我会使用哪个回调来停止 wiremock 服务器。
  • 最佳答案

    在类似情况下对我有用的方法:
    创建了一个自己的注释并在那里指定扩展

    @Inherited
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @ExtendWith(
    {
    MyWiremockExtension.class,
    SpringExtension.class,
    }
    )
    public @interface WireMockSpringTest {
    这在我的情况下保留了顺序

    关于java - 如何在 Junit 5 *before* Spring 测试上下文加载之前获得回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65193397/

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