2017-07-26 28 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()