我正在尝试为我的spring-integration流编写一个集成测试。我想用
MockRestServiceServer记录(使用http:outbound-gateway)传出的请求并将其匹配到Rest服务器。但是,当我调用模拟服务器的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());
}

最佳答案

经过数小时的调试,我意识到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();
}


我认为应该将其视为错误,因为我认为必须在应用程序执行后执行断言。

07-26 00:31