MockRestServiceServer模拟集成测试中的后端超时 [英] MockRestServiceServer simulate backend timeout in integration test

查看:1030
本文介绍了MockRestServiceServer模拟集成测试中的后端超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 realise test this 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模拟集成测试中的后端超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆