java MockRestServiceServer 转义 url 中的字符

标签 java unit-testing mockito

在我们的项目中,我们使用具有非常不寻常的 REST API 的外部系统。 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。但这没有帮助。

最佳答案

此问题已解决

URLEncoder.encode()

测试中

关于java MockRestServiceServer 转义 url 中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45332277/

相关文章:

java - 从一个类获取文本字段信息并将其显示在另一类的 JTextArea 上

java - 修改公共(public)静态最终数组

java - 将链式方法与 Graphics2D 一起使用

java - 验证是否使用 mockito 调用了三种方法之一

java - 每次和任何测试用例初始化 mockito 时出错

java - 如何在 Java 的同一测试中模拟具有多个端点的 REST 服务器?

java - 通过JSP显示BLOB(图像)

javascript - karma 单元测试 : Module name "react" has not been loaded yet for context: _. 使用 require([])

angular - 为什么我的异步 Angular Jasmine 单元测试不工作?

unit-testing - Mockito 使用不同的 Class 参数调用相同的方法