I have a @SpringBootTest with 2 tests of a service (happy + negative flows) which calls an external API. I used wiremock to stub the response of that API. When I run each test individually they pass, but when I run the entire class the second test fails. I assumed it’s because of the stub not being properly cleaned and as a solution I did a `WireMock.reset()` before each test. This doesn’t fix the issue. However, @DirtiesContext on the first test seems to fix it. I wish I didn’t have to use this annotation as it slows down the tests and is a bad practice all together to refresh the spring context after each test.
The tests look like this:
@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("/graphql")));
}
@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("/graphql")));
}
private static HttpHeaders createRestResponseHeaders() {
return new HttpHeaders(
new HttpHeader("Accept", "application/json"),
new HttpHeader("Content-type", "application/json")
);
}
}
Tried WireMock.reset() to reset the stubs before each test.
Tried adding scenarios to each stub.