問題描述
我正在使用 MockRestServiceServer 在我的 REST 控制器上編寫某種集成測試來模擬后端行為.我現在想要實現的是模擬來自后端的非常慢的響應,這最終會導致我的應用程序超時.似乎可以使用 WireMock 實現,但目前我想堅持使用 MockRestServiceServer.
I am writing some kind of integration test on my REST controller using MockRestServiceServer to mock backend behaviour. What I am trying to achieve now is to simulate very slow response from backend which would finally lead to timeout in my application. It seems that it can be implemented with WireMock but at the moment I would like to stick to MockRestServiceServer.
我正在創建這樣的服務器:
I am creating server like this:
myMock = MockRestServiceServer.createServer(asyncRestTemplate);
然后我在嘲笑我的后端行為:
And then I'm mocking my backend behaviour like:
myMock.expect(requestTo("http://myfakeurl.blabla"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(myJsonResponse, MediaType.APPLICATION_JSON));
是否可以為響應添加某種延遲或超時或其他類型的延遲(或者可能是整個模擬服務器,甚至是我的 asyncRestTemplate)?或者我應該切換到 WireMock 還是 Restito?
Is it possible to add some kind of a delay or timeout or other kind of latency to the response (or maybe whole mocked server or even my asyncRestTemplate)? Or should I just switch to WireMock or maybe Restito?
推薦答案
你可以這樣實現這個測試功能(Java 8):
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);
});
但是,我應該警告您,由于 MockRestServiceServer 只是替換了 RestTemplate requestFactory,因此您所做的任何 requestFactory 設置都將在測試環境中丟失.
But, I should warn you, that since MockRestServiceServer simply replaces RestTemplate requestFactory any requestFactory settings you'd make will be lost in test environment.
這篇關于MockRestServiceServer 在集成測試中模擬后端超時的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!