Wiremock 不会模拟 Web 客户端请求



我使用的是spring-boot 2.5.7、java8和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>

我的集成测试类:

@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模拟的代码片段:

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((阶段失败。

错误仅为:

原因:java.net.ConnectException:连接被拒绝:不再信息

如果将http://localhost:8443硬编码为WebClient的基本URL,则需要确保在端口8443上运行WireMock。

现在,您可以在随机端口@AutoConfigureWireMock(port = 0)上启动WireMock。如果您动态覆盖WebClient的基本URL,例如将其外包给配置值,这也是可能的。

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

相关内容

  • 没有找到相关文章

最新更新