How to use MockRestServiceServer with multiple URLs?
Asked Answered
K

2

4

I need to configure multiple expectations on an instance of MockRestServiceServer. The expectations are for two different URLs:

  1. Call URL #1
  2. Call URL #1 (for a second time)
  3. 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?

Kayne answered 8/11, 2016 at 20:8 Comment(0)
A
2

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
Arlenarlena answered 26/4, 2022 at 7:7 Comment(0)
C
0

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

Coquetry answered 16/11, 2017 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.