I am using spring boot 2.5.7, java 8 and 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>
My integration test 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());
}
}
Code piece to be mocked by wiremock inside my implementation 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();
Due to it can't be mocked, test failing at postPartInspectionImageModelToML.block() phase.
Error is only:
Caused by: java.net.ConnectException: Connection refused: no further information