如何在JUnit 5测试中使用WireMock的响应模板

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

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

这是一段示例代码:


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")

  • 尝试更改测试用例以使用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。

    但是以上所有变体均无效。有什么我想念的吗?

    我正在尝试使用WireMock的响应模板功能,但似乎无法与文档中提供的示例代码一起使用。这是一段示例代码:import static com ....

    java wiremock
    1个回答
    1
    投票

    @Rule方法将不起作用,因为当您自己在WireMockServer中创建新的规则时,您将忽略由规则创建/管理的@BeforeEach

    © www.soinside.com 2019 - 2024. All rights reserved.