How to add response delay with MockRestServiceServer for timeout testing

I’m working on integration tests for my REST controller and need to test timeout scenarios. I’m using MockRestServiceServer to mock my backend services but I can’t figure out how to simulate slow responses that would trigger timeouts in my app.

Here’s how I set up my mock server:

backendMock = MockRestServiceServer.createServer(restTemplate);

And this is how I configure the mock responses:

backendMock.expect(requestTo("http://test-api.example.com/data"))
    .andExpected(method(HttpMethod.POST))
    .andRespond(withSuccess(responseData, MediaType.APPLICATION_JSON));

Is there a way to introduce artificial delays or latency into MockRestServiceServer responses? I need to test how my application handles backend timeouts. Should I consider switching to a different mocking framework that supports this feature better?

yep, a Thread.sleep() in a custom ResponseCreator can do the trick, but it’s kinda messy. for timeout tests, you might want to use WireMock instead - it has built-in delays that are way easier to work with than MockRestServiceServer.

Interesting challenge! Have you tried making a custom ResponseCreator that blocks before returning? You could implement your own creator that waits before calling the actual response method. What timeout values are you testing against? Also, have you considered using testcontainers with a real server where you can control response timing?