MockRestServiceServer simulate backend timeout in integration test

霸气de小男生 提交于 2019-12-04 00:45:42

You can implement this test functionality this way (Java 8):

myMock
    .expect(requestTo("http://myfakeurl.blabla"))
    .andExpect(method(HttpMethod.GET))
    .andRespond(request -> {
        try {
            Thread.sleep(TimeUnit.SECONDS.toMillis(1));
        } catch (InterruptedException ignored) {}
        return new MockClientHttpResponse(myJsonResponse, HttpStatus.OK);
    });

But, I should warn you, that since MockRestServiceServer simply replaces RestTemplate requestFactory any requestFactory settings you'd make will be lost in test environment.

Approach that you can go for: Specifying the responsebody either with Class Path resource or normal string content. More detailed version of what Skeeve suggested above

.andRespond(request -> {
            try {
                Thread.sleep(TimeUnit.SECONDS.toMillis(5)); // Delay
            } catch (InterruptedException ignored) {}
            return withStatus(OK).body(responseBody).contentType(MediaType.APPLICATION_JSON).createResponse(request);
        });

In Restito, there is a buil-in function to simulate timeout:

import static com.xebialabs.restito.semantics.Action.delay

whenHttp(server).
   match(get("/something")).
   then(delay(201), stringContent("{}"))

In general, you can define your custom request handler, and do a nasty Thread.sleep() there.

This would be possible in Restito with something like this.

Action waitSomeTime = Action.custom(input -> {
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    return input;
});

whenHttp(server).match(get("/asd"))
        .then(waitSomeTime, ok(), stringContent("Hello World"))

Not sure about Spring, however. You can easily try. Check DefaultResponseCreator for inspiration.

If you control timeout in your http client and use for example 1 seconds you can use mock server delay

new MockServerClient("localhost", 1080)
.when(
    request()
        .withPath("/some/path")
)
.respond(
    response()
        .withBody("some_response_body")
        .withDelay(TimeUnit.SECONDS, 10)
);

If you want to drop connection in Mock Server use mock server error action

new MockServerClient("localhost", 1080)
.when(
    request()
        .withPath("/some/path")
)
.error(
    error()
        .withDropConnection(true)
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!