Home > Blockchain >  How to simulate ReadTimeoutException in Spock with Micronaut
How to simulate ReadTimeoutException in Spock with Micronaut

Time:12-18

I am trying to simulate io.micronaut.http.client.exceptions.ReadTimeoutException with Spock, but explicitly the exception cannot be thrown, as it cannot be accessed from the test class.

The code which I want to test is given below:

        try {
             res = httpClient.toBlocking().exchange(
                    HttpRequest.GET(url)
                            .header("env", "internal")
                            .header("Content-Type", "application/json"),
                    TokenResponseBody.class
            );

        } catch (HttpClientResponseException e) {
            LOGGER.error("Visa Token get request", e);
            throw new CardTokenException(String.valueOf(e.getStatus().getCode()), e.getMessage());
        } catch (ReadTimeoutException re) {
            LOGGER.error("Visa Token get request", re);
            throw new CardTokenException(re.getMessage(), "Tokens client read timeout");
        }

So I am trying to stub the BlockingHttpClient which is returned by the httpClient.toBlocking() like this:

BlockingHttpClient blockingHttpClientStub = Stub(BlockingHttpClient.class)
blockingHttpClientStub.exchange(
        _ as MutableHttpRequest, TokenResponseBody.class
) >> {
      MutableHttpRequest obj, Class classType -> new Thread().sleep(15000)
}
httpClient.toBlocking() >> blockingHttpClientStub

the default config duration is 10 seconds, so I am assuming the sleep method would interrupt it for 15 seconds and ReadTimeoutException will be thrown. Please help me out if there any way to simulate the the ReadTimeoutException.

CodePudding user response:

How do you figure that new Thread().sleep(15000) will block anything? You are creating a separate thread then you then try to sleep, before it even started. You can try Thread.currentThread().sleep(). However, you are basically replacing the whole implementation, so there is nothing to throw the exception.

Why don't you simply throw the exception?

BlockingHttpClient blockingHttpClientStub = Stub(BlockingHttpClient) {
    exchange(_ as MutableHttpRequest, TokenResponseBody) >> {
        throw io.micronaut.http.client.exceptions.ReadTimeoutException.TIMEOUT_EXCEPTION
    }
}
httpClient.toBlocking() >> blockingHttpClientStub
  • Related