java MockRestServiceServer在url中转义字符

时间:2017-07-26 16:10:23

标签: java unit-testing mockito

在我们的项目中,我们使用具有非常不寻常的REST API的外部系统。 它在网址中包含方括号:

api/v1/series?match[]=up

现在我们要测试自己的REST api,并且只是为了模拟这个外部系统的响应。 所以我们在单元测试中使用MockRestServiceServer对象。

    mockServer = MockRestServiceServer.createServer(restTemplate);
    mockServer.expect(ExpectedCount.manyTimes(), requestTo(UriComponentsBuilder.fromHttpUrl(prometheusURL + "series?match[]=up")
            .build().toUri()))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(promResponseMetricUpInfo, MediaType.APPLICATION_JSON));

在我们的服务中,我们只需将此外部API称为

restTemplate.getForObject(prometheusURL + "series?match[]=up", ResponseObjectForSeries.class);

但结果我们遇到以下错误:

java.lang.AssertionError: Unexpected request expected:<http://localhost:9090/api/v1/series?match[]=up> but was:<http://localhost:9090/api/v1/series?match%5B%5D=up>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.match.MockRestRequestMatchers$5.match(MockRestRequestMatchers.java:121) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.DefaultRequestExpectation.match(DefaultRequestExpectation.java:84) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.SimpleRequestExpectationManager.validateRequestInternal(SimpleRequestExpectationManager.java:55) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.AbstractRequestExpectationManager.validateRequest(AbstractRequestExpectationManager.java:75) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.MockRestServiceServer$MockClientHttpRequestFactory$1.executeInternal(MockRestServiceServer.java:289) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.mock.http.client.MockClientHttpRequest.execute(MockClientHttpRequest.java:94) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:652) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]

我们如何逃避这些方括号? 我试图在测试中使用反斜杠或%5B%5D明确。但它没有帮助。

1 个答案:

答案 0 :(得分:0)

使用

解决了此问题
URLEncoder.encode()

在测试中