在 Spring boot 中启用 WireMock 规则

问题描述 投票:0回答:2

我正在尝试为 Wiremock 启用响应模板。 文档声明需要添加以下代码:

@Rule
public WireMockRule wm = new WireMockRule(options()
    .extensions(new ResponseTemplateTransformer(false))
);

但是,这个 @Rule 注释是针对 JUnit 的,目前,我没有在 junit 测试中运行 wiremock。那么,有没有办法在应用范围内开启WireMockRule呢?

java spring-boot wiremock
2个回答
0
投票

要在 Spring Boot 应用程序中启用 WireMock,您可以使用 wiremock-jre8 依赖项中的 WireMockRule 类。以下是步骤:

  1. 将 wiremock-jre8 依赖项添加到项目的 pom.xml
<!-- 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'
  1. 创建一个测试类并用
    @RunWith(SpringRunner.class)
    注释它。
  2. 为 WireMockRule 创建一个字段并用 @Rule 注释它:
@Rule
public WireMockRule wireMockRule = new WireMockRule(options().port(8080));
  1. 在您的测试方法中,使用 WireMockRule 来存根您的外部服务所需的行为:
@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 将在其上运行的端口。您可以将其更改为您喜欢的任何可用端口。


0
投票

只需要在使用 WireMockConfiguration 初始化 WireMockServer 时添加扩展。

WireMockServer server = new WireMockServer(new WireMockConfiguration().port(PORT).extensions(new ResponseTemplateTransformer(false)));
    
© www.soinside.com 2019 - 2024. All rights reserved.