Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expect requestTo by String pattern in MockRestServiceServer?

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?

like image 417
Justinas Jakavonis Avatar asked Feb 18 '19 11:02

Justinas Jakavonis


Video Answer


1 Answers

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));
like image 84
amseager Avatar answered Oct 17 '22 15:10

amseager