java - 如何在 Junit 5 *before* Spring 测试上下文加载之前获取回调?
问题描述
在运行任何测试之前,我正在使用 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
,或 - extend
SpringBootTestContextBootstrapper
,覆盖buildTestContext()
在调用之前启动wiremocksuper.buildTestContext()
,然后@BootstrapWith
是我的类而不是Spring Boot的类,尽管我不确定我会使用哪个回调来停止wiremock服务器。
解决方案
这对我有用:
- 使用 Spring TestContext 框架实现它,这也使它与 TestNG 一起工作
- 实施
TestExecutionListener
- 使测试执行监听器实现
Ordered
- 实现
getOrder
并返回小于 2000 的值(DependencyInjectionTestExecutionListener 的顺序)
推荐阅读
- python - 我不知道交互式任务中的标准输出有什么问题,测试系统说发生了空闲限制超出
- flutter - 为什么两个容器之间有一条白线颤动
- c - 垃圾收集如何与数据段一起工作?
- design-patterns - Flyweight 设计模式是否适用于降低实例化成本?
- python - Python - 遍历嵌套字典并获取值
- python - 散景图 y_range 坐标偏离半个坐标
- python - Python动画奇怪的行为
- java - 不相交集数据结构是否在 Java 中本地实现?
- sql - 如何使用算术运算创建 Cloudant 查询
- python - Pandas groupby() .sum() 多次返回行值而不是 sum