2017-07-26 103 views
1

在我们的项目中,我们使用的是外部系统和非常不寻常的REST API。 它包含方括号中的网址:java MockRestServiceServer URL中的转义字符

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显式。但它没有帮助。

+0

你如何尝试%5B%5D明确解决?你介意与我们分享代码吗? –

+0

我的意思是我刚刚写了mockServer.expect(ExpectedCount.manyTimes(),requestTo(UriComponentsBuilder.fromHttpUrl(prometheusURL +“series?match%5B%5D = up”)),但这些符号也是编码的。编码两次 –

+0

如果你删除toUri()它的作品? – user7294900

回答

0

这个问题在测试中使用

URLEncoder.encode()