8

我有测试:

org.springframework.test.web.client.MockRestServiceServer mockServer

当我使用any(String.class)或确切的 URL 运行时,它们运行良好:

mockServer.expect(requestTo(any(String.class)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));

或者:

mockServer.expect(requestTo("https://exact-example-url.com/path"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));

我希望通过字符串模式请求来避免检查确切的 URL。我可以编写自定义匹配器,如Spring MockRestServiceServer 处理对同一 URI 的多个请求(自动发现)

有没有其他方法可以mockServer.expect(requestTo(".*example.*"))通过字符串模式制作?

4

1 回答 1

13

I suppose that "any" is actually a Mockito.any() method? In that case you can rather use Mockito.matches("regex"). See docs: https://static.javadoc.io/org.mockito/mockito-core/1.9.5/org/mockito/Matchers.html#matches(java.lang.String)


EDIT: It turns out that MockRestServiceServer uses Hamcrest matchers to verify the expectations (methods like requestTo, withSuccess etc.).

There is also a method matchesPattern(java.util.regex.Pattern pattern) in org/hamcrest/Matchers class which is available since Hamcrest 2, and it can be used to solve your problem.

But in your project you probably have the dependency on the older version of Hamcrest (1.3) which is used by, for example, junit 4.12, the latest spring-boot-starter-test-2.13, or, finally, org.mock-server.mockserver-netty.3.10.8 (transitively).

So, you need to:

  1. Check the actual version of Hamcrest in your project and (if it's not 2+) update this dependency manually: https://mvnrepository.com/artifact/org.hamcrest/hamcrest/2.1
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.1</version>
    <scope>test</scope>
</dependency>
  1. Update your test:
mockServer.expect(requestTo(matchesPattern(".*exact-example-url.com.*")))
    .andExpect(method(HttpMethod.GET))
    .andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
于 2019-02-19T23:34:59.317 回答