首页 > 解决方案 > 如何在 JUnit 5 测试中使用 WireMock 的响应模板

问题描述

我正在尝试使用 WireMock 的响应模板功能,但它似乎不适用于文档中提供的示例代码。

这是一段示例代码:


import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.restassured.RestAssured;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class WireMockTest {

  @Rule
  public WireMockRule wm = new WireMockRule(options()
      .extensions(new ResponseTemplateTransformer(true)));
  private WireMockServer wireMockServer;

  @BeforeEach
  public void setup() {
    this.wireMockServer = new WireMockServer(
        options().port(8081));
    this.wireMockServer.stubFor(get(urlEqualTo("/test-url"))
        .willReturn(aResponse()
            .withBody("{{request.url}}")
            .withTransformers("response-template")));
    this.wireMockServer.start();
  }

  @Test
  public void test() {
    RestAssured.when()
        .get("http://localhost:8081/test-url")
        .then()
        .log().ifError()
        .body(Matchers.equalTo("/test-url"));
  }

  @AfterEach
  public void tearDown() {
    wireMockServer.stop();
  }
}

预期输出:

测试应该通过。(意味着 {{request.url}} 应该被替换/test-url为模板渲染的结果)。

实际输出:

....

java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: "/test-url"
  Actual: {{request.url}}

我尝试过的事情:

  1. 由于这些是使用 JUnit 5 API 的测试用例,因此没有@Rule WireMockRule添加.withTransformers("response-template").
  2. 尝试更改测试用例以使用 JUnit 4 API,并添加
@Rule
public WireMockRule wm = new WireMockRule(options()
    .extensions(new ResponseTemplateTransformer(false))
);

(连同withTransformers
3. 更改WireMockRule

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

(连同 withTransformers)
4. 删除了withTransformers唯一保留的WireMockRule. (JUnit 4)
5. 我也尝试过上述与 JUnit 5 API 的组合。

但上述变化都没有奏效。有什么我想念的吗?

标签: javawiremock

解决方案


@Rule方法不起作用,因为您WireMockServer@BeforeEach.

您应该删除规则并将其添加到ResponseTemplateTransformer通过对象中。@BeforeEachWireMockServerOptions

像这样的东西应该可以解决问题(从 Javadoc 来看)。

@BeforeEach
  public void setup() {
    this.wireMockServer = new WireMockServer(
        options()
          .extensions(new ResponseTemplateTransformer(false))
          .port(8081));
    this.wireMockServer.stubFor(get(urlEqualTo("/test-url"))
        .willReturn(aResponse()
            .withBody("{{request.url}}")
            .withTransformers("response-template")));
    this.wireMockServer.start();
  }

推荐阅读