MockRestServiceServer无法正确验证请求

时间:2015-10-26 20:27:15

标签: spring testing integration-testing spring-integration spring-test

我试图为我的spring-integration流程编写集成测试。我想用 MockRestServiceServer用于记录和匹配传出请求(使用http:outbound-gateway)到Rest服务器。但是,当我调用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的验证方法时,它没有调用RequestMatchers的匹配方法,我相信这个逻辑有问题。我在这里错过了什么吗?

/**
 * 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());
}

2 个答案:

答案 0 :(得分:2)

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

我认为这应该被视为一个错误,因为我认为断言必须在应用程序执行后执行。

答案 1 :(得分:0)

之前我没有使用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

因此,只有在您使用经过修改的RequestMatchers时,才能调用RestTemplate

因此,您必须将其注入<int-http:outbound-gateway>。 或者甚至更好地共享该网关与此RestTemplate之间的MockRestServiceServer实例。