我正在尝试为我的spring-集成流编写一个集成测试。我想使用MockRestServiceServer记录并匹配到Rest服务器的传出请求(使用http:outbound-gateway)。但是,当我调用mockServer的verify方法时,它并没有像预期的那样进行验证。
我用下面的方式写测试:
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("adfasfadf.com")).andExpect(method(HttpMethod.GET));
// Call spring integration flow here
mockServer.verify();当我检查MockRestServiceServer的verify方法时,它没有调用RequestMatchers的match方法,我认为这个逻辑有问题。我是不是漏掉了什么?
/**
* Verify that all expected requests set up via
* {@link #expect(RequestMatcher)} were indeed performed.
* @throws AssertionError when some expectations were not met
*/
public void verify() {
if (this.expectedRequests.isEmpty() || this.expectedRequests.equals(this.actualRequests)) {
return;
}
throw new AssertionError(getVerifyMessage());
}发布于 2015-10-27 17:28:13
经过几个小时的调试,我意识到MockRestServiceServer会在请求执行期间运行匹配器。因此,如果您在请求执行周围有一个异常处理程序,您的断言将永远不会被正确断言。这段代码来自运行匹配器的RequestMatcherClientHttpRequest。
@Override
public ClientHttpResponse executeInternal() throws IOException {
if (this.requestMatchers.isEmpty()) {
throw new AssertionError("No request expectations to execute");
}
if (this.responseCreator == null) {
throw new AssertionError("No ResponseCreator was set up. Add it after request expectations, "
+ "e.g. MockRestServiceServer.expect(requestTo(\"/foo\")).andRespond(withSuccess())");
}
for (RequestMatcher requestMatcher : this.requestMatchers) {
requestMatcher.match(this);
}
setResponse(this.responseCreator.createResponse(this));
return super.executeInternal();
}我认为这应该被认为是一个错误,因为我认为断言必须在应用程序执行之后执行。
发布于 2015-10-27 06:22:06
我以前没有用过MockRestServiceServer,但看起来这是一个很棒的功能。谢谢你指出这一点!
无论如何,根据它的源代码,我们有:
public static MockRestServiceServer createServer(RestTemplate restTemplate) {
Assert.notNull(restTemplate, "'restTemplate' must not be null");
MockRestServiceServer mockServer = new MockRestServiceServer();
RequestMatcherClientHttpRequestFactory factory = mockServer.new RequestMatcherClientHttpRequestFactory();
restTemplate.setRequestFactory(factory);
return mockServer;
}请注意RequestMatcherClientHttpRequestFactory。
因此,只有使用修改后的RestTemplate,才能调用您的RequestMatchers。
因此你必须把它注入到你的<int-http:outbound-gateway>中。或者更好地在该网关和该MockRestServiceServer之间共享RestTemplate实例。
https://stackoverflow.com/questions/33354960
复制相似问题