I have tests with:
org.springframework.test.web.client.MockRestServiceServer mockServer
When I run with any(String.class)
or exact URL they work well:
mockServer.expect(requestTo(any(String.class)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
Or:
mockServer.expect(requestTo("https://exact-example-url.com/path"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
I want to expect request by String pattern to avoid checking exact URL. I can write custom matcher like on Spring MockRestServiceServer handling multiple requests to the same URI (auto-discovery)
Is there any other way to make mockServer.expect(requestTo(".*example.*"))
by String pattern?
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:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.1</version>
<scope>test</scope>
</dependency>
mockServer.expect(requestTo(matchesPattern(".*exact-example-url.com.*")))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With