Spring MockRestServiceServer handling multiple requests to the same URI (auto-discovery)

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 08:25:02
emeraldjava

If you look at the MockRestServiceServer class, it supports two 'expect()' methods. The first defaults to 'ExpectedCount.once()' but the second method allows you change this value

public ResponseActions expect(RequestMatcher matcher) {
    return this.expect(ExpectedCount.once(), matcher);
}

public ResponseActions expect(ExpectedCount count, RequestMatcher matcher) {
    return this.expectationManager.expectRequest(count, matcher);
}

I found this ticket MockRestServiceServer should allow for an expectation to occur multiple times which outlines some options for second method.

In your case I think adding static import and using the manyTimes() method is neater code than the for loop

MockRestServiceServer
            .expect(manyTimes(), requestContainsUri("/stuff"))
            .andExpect(method(HttpMethod.GET))

Other options are

once();
manyTimes();
times(5);
min(2);
max(8);
between(3,6);

EDIT: See answer from @emeraldjava which shows the correct solution for Spring 4.3+ users.

Unfortunately there isn't any nice mechanism to expect multiple calls. You either do it manually or use loops, e.g.:

for (int i = 0; i < 10; i++) {           
        mockRestServiceServer
                .expect(requestContainsUri("/stuff"))
                .andExpect(method(HttpMethod.GET))
                .andRespond(withAutoDetectedCannedData());
}

Be aware that the requests must be called without any interruptions, e.g. there cannot be another REST call that doesn't match the "/stuff" URI.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!