Sjoerd During
Sjoerd During

Reputation: 121

How to mock multiple responses for same request using spring's MockRestServiceServer?

Im using MockRestServiceServer for mocking http responses. In a specific scenario i call an endpoint two times and want a different response the second time.

But when i write a second expectation it's like it overwrites my first expectation.

How does one write multiple responses for the same request?

Upvotes: 8

Views: 4255

Answers (2)

Madhu Bhat
Madhu Bhat

Reputation: 15183

Have you tried WireMock? It's amazing and provides many features to mock APIs. Have a look at http://wiremock.org/

Upvotes: 0

Sjoerd During
Sjoerd During

Reputation: 121

I've found it after some research:

When instantiating a MockRestServiceServer it default gets an UnorderedRequestExpectationManager. Changing this via the Builder in a SimpleRequestExpectationManager adds support for adding multiple responses in the order of defining them.

private MockRestServiceServer createMockServerBy(Class<? extends 
RestTemplate> requiredType) {
    RestTemplate template = context.getBean(requiredType);
    return MockRestServiceServer.bindTo(template).build(new 
    SimpleRequestExpectationManager());
}

Upvotes: 4

Related Questions