Тесты выглядят следующим образом:
Код: Выделить всё
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@AutoConfigureWireMock(port = 0)
public class ServiceClientTest{
private static final String EXPECTED_NAME = "dummy";
private static final String ID = "123";
private static final String PERSON_NUMBER = "1234";
// under test
@Autowired
private ServiceClient serviceClient;
@AfterEach
public void setUp() {
WireMock.reset();
}
@Test
// @DirtiesContext -> this fixes the tests
public void testGetName() {
stubFor(post(urlPathEqualTo("/externalAPI")).withRequestBody(equalToJson(getBody()))
.willReturn(aResponse()
.withHeaders(createRestResponseHeaders())
.withStatus(200)
.withBody(getResponse())));
Name name = serviceClient.getName(PERSON_NUMBER, ID);
assertThat(name.getValue()).isEqualTo(EXPECTED_NAME);
verify(postRequestedFor(urlPathEqualTo("/externalAPI")));
}
@Test
public void testGetName_BadRequest() {
WireMock.stubFor(WireMock.any(urlPathEqualTo("/externalAPI"))
.willReturn(aResponse()
.withHeaders(createRestResponseHeaders())
.withStatus(HttpStatus.BAD_REQUEST.value())));
assertThatThrownBy(() ->
serviceClient.getName(PERSON_NUMBER, ID))
.isInstanceOf(BadResponseException.class);
verify(postRequestedFor(urlPathEqualTo("/externalAPI")));
}
private static HttpHeaders createRestResponseHeaders() {
return new HttpHeaders(
new HttpHeader("Accept", "application/json"),
new HttpHeader("Content-type", "application/json")
);
}
}
Попробовал добавить сценарии к каждой заглушке.
Подробнее здесь: https://stackoverflow.com/questions/786 ... after-test