javatestingmockingmockserverawaitility

MockServer. Verify call happends within x seconds


I am trying to write an integration test using MockServer (https://www.mock-server.com) and I would like to verify that a request was called on the mock after running the asynchronous anAsyncMethodThatReturnsImmediatly() method on the tested class sut. My problem is that the test terminates before the call happens.

I have the following code:

@Test
void test() {
    HttpRequest httpRequest = HttpRequest.request()
            .withMethod(HttpMethod.POST.name())
            .withPath(MY_ENDPOINT);

    HttpResponse httpResponse = HttpResponse.response().withStatusCode(200);

    mockClient.when(httpRequest).respond(httpResponse);

    sut.anAsyncMethodThatReturnsImmediatly();

    long then = System.currentTimeMillis() + 1_000L;
    Awaitility.await().until(() -> System.currentTimeMillis() > then);

    mockClient.verify(httpRequest, VerificationTimes.exactly(1));

}

That works, but if I remove the waiting part, then it fails, because sut.anAsyncMethodThatReturnsImmediatly() is asynchronous and returns immediately, and we end up calling verify, before the call happens.

I don't have any condition to wait for, because that call is fire and forget, we do not wait for the response.

That 1s wait in the middle of the code looks plain wrong to me.

Is there a way to test this with MockServer? something like verify call happens within x second?

EDIT: I improved over the plain wait this way. That is fine. still open to better solutions though.

Awaitility.await().atMost(Duration.ofSeconds(5)).until(() -> {
    try {
        mockClient.verify(httpRequest, VerificationTimes.exactly(1));
        return true;
    } catch (AssertionError ex) {
        return false;
    }
});

Solution

  • Found a solution for my use case, leaving it here:

    Awaitility.await()
              .atMost(Duration.ofSeconds(5))
              .untilAsserted(() -> 
                   mockClient.verify(httpRequest, VerificationTimes.exactly(1))
               );