【问题标题】:WireMock not intercepting http request with Spring boot Integration TestWireMock 未使用 Spring Boot 集成测试拦截 http 请求
【发布时间】:2020-11-19 12:58:15
【问题描述】:

我使用 Wiremock 进行了 Sprint Boot 集成测试,但由于某种原因,Wiremock 不提供存根响应,并且 http 请求发送到实际的外部 api。我错过了什么吗?我可以从日志中看到 Wiremock 服务器正在端口 8888 上启动

   <dependency>
        <groupId>com.github.tomakehurst</groupId>
        <artifactId>wiremock-jre8-standalone</artifactId>
        <version>2.27.0</version>
        <scope>test</scope>
    </dependency>



@RunWith(SpringRunner.class)
@SpringBootTest(classes = GatewayApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RegTypeIntegratedTest {

    @LocalServerPort
    private int port;

    TestRestTemplate restTemplate = new TestRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    ObjectMapper mapper = new ObjectMapper();

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(options().port(8888));


    @Test
    public void testRegType()
            throws JSONException, JsonParseException, JsonMappingException, FileNotFoundException, IOException {

        wireMockRule.stubFor(post(urlPathMatching("{path}/.*/")).willReturn(
                aResponse().withHeader("Content-Type", "application/json").withBody(new String(Files.readAllBytes(
                        Paths.get("path/regtypeResponse_stub.json"))))));


        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/{service-url-path}y/regTypes?regtype=I"), HttpMethod.GET, entity,
                String.class);

        String expected = new String(Files
                .readAllBytes(Paths.get("path/regtypeResponse_expected.json")));

        JSONAssert.assertEquals(expected, response.getBody(), true);
    }

    private String createURLWithPort(String uri) {
        return "http://localhost:" + port + uri;
    }
}

【问题讨论】:

  • 我认为这是使用 HTTP 方法的一些疏忽的情况,但现在我和 cobz 一样困惑。你能解释一下为什么需要 WireMock 和 Spring Boot 服务器吗?

标签: spring-boot integration-testing wiremock


【解决方案1】:

我认为您混淆了 SpringBootTest 中运行的两个不同服务器的信息。一方面,您告诉您的单元测试让您的实际 Spring Boot 应用程序在随机 Web 端口上运行以进行测试,以模拟对您的 Web 应用程序的真实调用。 spring 应用程序分配给您的这个端口被拉入您的port 变量。

同时,您正在端口 8888 上设置 Wiremock,您还可以按照说明在日志中观察到。

在您的测试中,您现在通过 return "http://localhost:" + port... 调用已启动的 Spring Boot 应用程序的真实端口以进行测试,该端口在您对 RestTemplate 实例的调用中被引用。

我认为,当您真正想要调用正在运行的 spring 应用程序时,以及何时使用wiremock 调用外部端点模拟时,您需要分开。

【讨论】:

  • 我实际上错过了这里的基本概念,我没有将后端 api 配置为转到 Wiremock 实例,因此它将转到真实/实时 api。我的印象是 Wiremock 在 JUnit 中运行时会拦截。我将端点配置为 Wiremock 端点并且一切正常
【解决方案2】:

您为 WireMock 服务器的 POST 方法存根,但随后您在 TestRestTemplate 客户端中调用 GET 方法。

你也没有扩展你的路径变量{service-url-path}

【讨论】:

  • 我在这里测试的 API 是 GET,但是从这个被测 API 调用的后端 API(存根)是 POST。
猜你喜欢
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 2022-11-10
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多