Wiremock 不会模拟 Web 客户端请求

Wiremock Doesn't Mock the Webclient Request

我正在使用 spring boot 2.5.7、java 8 和 junit 5。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.7</version>
    <relativePath />
</parent>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-contract-wiremock</artifactId>
        <version>3.0.4</version>
        <scope>test</scope>
    </dependency>

我的集成测试class:

@SpringBootTest(classes = MyTestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWireMock(port = 0)
@DirtiesContext
public class MyTestControllerTest {

  @LocalServerPort
  private int port;

  @Autowired
  private TestRestTemplate restTemplate;

  @BeforeEach
  void init() {
    stubFor(post(urlPathEqualTo("http://localhost:8443/my-third-party-endpoint"))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader("Content-Type", MediaType.APPLICATION_JSON.toString())
            .withHeader("Accept", MediaType.APPLICATION_JSON.toString())
            .withBody("{}")));
  }

  @Test
  public void testAddEmployee() {
    PartInspectionImageModel partInspectionImageModel = new PartInspectionImageModelProvider().createPartInspectionImageModel();

    ResponseEntity<PartInspectionImageModel> responseEntity = this.restTemplate
        .postForEntity("http://localhost:" + port + "/rest/my-test-endpoint", partInspectionImageModel, PartInspectionImageModel.class);

    assertEquals(200, responseEntity.getStatusCodeValue());
  }
}

在我的实现中被 wiremock 模拟的代码片段 class:

 WebClient webClient = WebClient.create("http://localhost:8443");

  Mono<String> postPartInspectionImageModelToML = webClient.post()
      .uri("/my-third-party-endpoint")
      .contentType(MediaType.APPLICATION_JSON)
      .accept(MediaType.APPLICATION_JSON)
      .body(Mono.just(completeMlProcessingModel), CompleteMlProcessingModel.class)
      .retrieve()
      .bodyToMono(String.class);

  String response = postPartInspectionImageModelToML.block();

由于无法模拟,测试在 postPartInspectionImageModelToML.block() 阶段失败。

错误只有:

Caused by: java.net.ConnectException: Connection refused: no further information

如果您将 http://localhost:8443 硬编码为您的 WebClient.[=14= 的基础 URL,则需要确保您的 运行 WireMock 在端口 8443 上]

截至目前,您在随机端口 @AutoConfigureWireMock(port = 0) 上启动 WireMock。如果您通过例如动态覆盖 WebClient 的基础 URL ,这也是可能的。外包给一个配置值。

否则,尝试将其更改为@AutoConfigureWireMock(port = 8443)