Jus*_*tas 5 java junit mockito spring-boot mockserver
我有以下测试:
org.springframework.test.web.client.MockRestServiceServer mockServer
Run Code Online (Sandbox Code Playgroud)
当我使用any(String.class)或确切的 URL运行时,它们运行良好:
mockServer.expect(requestTo(any(String.class)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)
或者:
mockServer.expect(requestTo("https://exact-example-url.com/path"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)
我希望通过字符串模式请求避免检查确切的 URL。我可以在Spring MockRestServiceServer上编写自定义匹配器来处理对同一 URI 的多个请求(自动发现)
有没有其他方法可以mockServer.expect(requestTo(".*example.*"))通过 String 模式制作?
我想“any”实际上是一个 Mockito.any() 方法?在这种情况下,您可以使用 Mockito.matches("regex")。见文档:https ://static.javadoc.io/org.mockito/mockito-core/1.9.5/org/mockito/Matchers.html#matches( java.lang.String)
编辑:事实证明 MockRestServiceServer 使用 Hamcrest 匹配器来验证期望(像 requestTo、withSuccess 等方法)。
还有一种方法matchesPattern(java.util.regex.Pattern中图案)在组织/ hamcrest /匹配器类,这是因为Hamcrest 2可用的,并且它可以被用来解决问题。
但是在您的项目中,您可能依赖于旧版本的 Hamcrest (1.3),例如,junit 4.12、最新的 spring-boot-starter-test-2.13 或最后的 org.mock-server .mockserver-netty.3.10.8(传递)。
所以,你需要:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.1</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
mockServer.expect(requestTo(matchesPattern(".*exact-example-url.com.*")))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5907 次 |
| 最近记录: |