'How to use MockRestServiceServer with multiple URLs?
I need to configure multiple expectations on an instance of MockRestServiceServer. The expectations are for two different URLs:
- Call URL #1
- Call URL #1 (for a second time)
- Call URL #2
The same URL is called twice, then a 3rd call is made to the same URL with different request params.
I have one instance of a load-balanced RestTemplate available to inject into my test, and I pass this to MockRestServiceServer.createServer().
I've tried to inline these 3 expectations to my MockRestServiceServer instance but the test fails claiming the 3rd URL was expected but it saw the 1st. It seems like I'm either overwriting the expectations or there's something stateful being shared here that's keeping the mock server in the wrong state.
Can anyone show me an example of how to do this correctly?
Solution 1:[1]
In case anyone not able to understand @alex.b reply
// Create a mock server with UnorderedRequestExpectationManager
MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build(new UnorderedRequestExpectationManager());
// Add multiple rest url
mockServer.expect(ExpectedCount.once(),
requestTo(URL1))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(result1));
mockServer.expect(ExpectedCount.once(),
requestTo(URL2))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(result2));
// Add as much as you want
Solution 2:[2]
Your problem can be solved if you use not default expectation manager within the Mock Server org.springframework.test.web.client.MockRestServiceServer#MockRestServiceServer
: it accepts a parameter of org.springframework.test.web.client.RequestExpectationManager
.
You can pass this type: org.springframework.test.web.client.UnorderedRequestExpectationManager
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Puneeth Rai |
Solution 2 | alex.b |