MockServer with test specific session id

426 views Asked by At

I use SpringBoot and Java to write e2e tests for my API. Along the flow, I am doing an HTTP call to a storage API (S3), and I am mocking it using MockServer.

This is the HttpClient and how I am creating my post request:

public class HttpClient {

    private final String baseUrl;

    public <T> Mono<T> post(final String path, String body, Class<T> responseType) {
        return WebClient.builder()
            .baseUrl(baseUrl) // localhost:1082
            .build()
            .post()
            .uri(path)
            .bodyValue(body)
            .accept(MediaType.APPLICATION_JSON)
...

This is how I am configuring my mock server:

public class CommonMockServerHelpers {

    private static MockServerClient mockServerClientStorage = new MockServerClient("localhost", 1082).reset();

    public static MockServerClient getClientStorage() {
        return mockServerClientStorage;
    }

    public static void verify(String path, String exceptedRequestBody, int times) {
        Awaitility.await()
            .atMost(Duration.ofSeconds(60))
            .untilAsserted(() ->
                verify(getClientStorage(), path, exceptedRequestBody, times)
            );
    }

    public static void verify(MockServerClient client, String path, String exceptedRequestBody, int times) {
        client.verify(buildPostRequest()
            .withBody(subString(exceptedRequestBody))
            .withPath(path), VerificationTimes.exactly(times));
    }

In my tests, I am making API HTTP calls using RestTemplate. In one test this verification should pass:

CommonMockServerHelpers.verify("/save-file", "FAILED", 0);

while on the other it should not. When running the test they collide and make each other fail. Is there a way to create some uniqueness to each test so I'll be able to verify the MockServer calls of a test without interfering with the other tests?

1

There are 1 answers

0
Obenland On

you should write expectations in each test case like this:

mockServerClientStorage.reset()
    .when(request()
            .withMethod("GET")
            .withPath("/save-file"))
    .respond(response()
            .withStatusCode(200)
            .withBody("Nice!"));
mockServerClientStorage.reset()
    .when(request()
            .withMethod("GET")
            .withPath("/save-file"))
    .respond(response()
            .withStatusCode(500)
            .withBody("I failed!"));

It's important to do the reset() first, because those expectation are saved by the mockServer and will result in flaky tests otherwise. You could do the reset() in a @beforeEach-method if you like.