簡體   English   中英

如何在 Junit 5 *before* Spring 測試上下文加載之前獲取回調?

[英]How to get callback in Junit 5 *before* Spring test context is loaded?

在運行任何測試之前,我正在使用 Junit 5 擴展來啟動 Wiremock 服務器。 但是,Spring 上下文中的一個 bean 進行遠程調用作為其初始化的一部分,我無法更改,並且該調用導致 ConnectionException,因為 Wiremock 服務器尚未啟動。

如何配置我的 JUnit 5 測試以在 Spring 加載文本上下文之前獲得回調?

我的 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 ,但這並沒有在測試上下文加載之前提供回調方法。

我對如何做到這一點的最佳猜測是:

  1. 創建我自己的ContextCustomizerFactory ,或
  2. 擴展SpringBootTestContextBootstrapper ,覆蓋buildTestContext()以在調用super.buildTestContext()之前啟動wiremock,然后@BootstrapWith我的 class 而不是 Spring Boot,雖然我不確定我會使用哪個回調來停止wiremock服務器。

在類似情況下對我有用的是:

創建了一個自己的注釋並在那里指定擴展

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(
    {
        MyWiremockExtension.class,
        SpringExtension.class,
    }
)
public @interface WireMockSpringTest {

在我的情況下,這保留了訂單

這對我有用:

  • 使用 Spring TestContext 框架實現它,這也使它與 TestNG 一起使用
  • 實現TestExecutionListener
  • 使測試執行監聽器實現Ordered
  • 實現getOrder並返回小於2000的值(DependencyInjectionTestExecutionListener的順序)

示例代碼https://github.com/marschall/spring-test-scope/blob/master/src/main/java/com/github/marschall/spring/test/scope/TestScopeTestExecutionListener.java

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM