首页 > 解决方案 > 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?

标签: springintegration-testingspring-test-mvcmockrestserviceserver

解决方案


经过一番研究,我发现了它:

当实例化一个 MockRestServiceServer 时,它默认获得一个 UnorderedRequestExpectationManager。通过 SimpleRequestExpectationManager 中的 Builder 进行更改,增加了对按定义顺序添加多个响应的支持。

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

推荐阅读