How to expect requestTo by String pattern in MockRestServiceServer?
Asked Answered
W

1

10

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?

Werby answered 18/2, 2019 at 11:6 Comment(0)
B
17

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));
Boadicea answered 19/2, 2019 at 23:34 Comment(3)
@Justas What do you mean by "expected empty URL". Is it some kind of exception or what?Boadicea
I get AssertionError: expected: <> but got "exact-example-url.com/path" when I do mockServer.expect(requestTo(Mockito.matches(".*example.*")))Werby
For those having the same issue as Justinas mentioned above, make sure you import/use a hamcrest matcher instead of a mockito matcher.Transfusion

© 2022 - 2024 — McMap. All rights reserved.