我使用的是spring 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>
我的集成测试课程:
@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:连接被拒绝:没有进一步的信息
发布于 2021-12-06 05:24:09
如果将WireMock硬编码为http://localhost:8443
作为WebClient
的基本URL,则需要确保在端口8443上运行WebClient
。
到目前为止,您可以在随机端口WireMock上启动@AutoConfigureWireMock(port = 0)
。如果您动态地重写您的WebClient的基本URL,例如将它外包给一个配置值,这也是可能的。
否则,尝试将其更改为@AutoConfigureWireMock(port = 8443)
。
https://stackoverflow.com/questions/70195846
复制相似问题