我正在尝试为 Wiremock 启用响应模板。 文档声明需要添加以下代码:
@Rule
public WireMockRule wm = new WireMockRule(options()
.extensions(new ResponseTemplateTransformer(false))
);
但是,这个 @Rule 注释是针对 JUnit 的,目前,我没有在 junit 测试中运行 wiremock。那么,有没有办法在应用范围内开启WireMockRule呢?
要在 Spring Boot 应用程序中启用 WireMock,您可以使用 wiremock-jre8 依赖项中的 WireMockRule 类。以下是步骤:
<!-- Maven -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.27.2</version>
<scope>test</scope>
</dependency>
或 build.gradle
testImplementation 'com.github.tomakehurst:wiremock-jre8:2.27.2'
@RunWith(SpringRunner.class)
注释它。@Rule
public WireMockRule wireMockRule = new WireMockRule(options().port(8080));
@Test
public void testMyService() {
stubFor(get(urlEqualTo("/my/resource"))
.willReturn(aResponse()
.withStatus(200)
.withBody("Hello, world!")));
// make a call to your service that depends on the external service
// and verify that it behaves as expected
}
请注意,步骤 3 中的 options().port(8080) 方法调用指定了 WireMock 将在其上运行的端口。您可以将其更改为您喜欢的任何可用端口。
只需要在使用 WireMockConfiguration 初始化 WireMockServer 时添加扩展。
WireMockServer server = new WireMockServer(new WireMockConfiguration().port(PORT).extensions(new ResponseTemplateTransformer(false)));