I have a @Component
DataClientImpl that calls a REST API using RestTemplate
. The API endpoint has query params, which are passed when calling RestTemplate
.
There is a @RestClientTest
Test class DataApiClientImplTest
testing the DataClientImpl
, mocking the REST calls using MockRestServiceServer
.
In the test method I want to verify that the correct endpoint path and query params (name particularly) are used in API call.
Using MockRestRequestMatchers.requestTo()
and MockRestRequestMatchers.queryParam()
methods to verify.
The MockRestRequestMatchers.requestTo()
fails when the test is run. It appears to compare the actual url include query string with expected url without query string (that is passed to MockRestRequestMatchers.requestTo()
method.
In the pom, I am using
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.0</version>
<relativePath/>
</parent>
Code below.
@RestClientTest(DataApiClientImpl.class)
@AutoConfigureWebClient(registerRestTemplate = true)
class DataApiClientImplTest {
private static final String OBJECT_ID_URI = "http://localhost:8080/testBucketId/objects/test-obj-id";
@Autowired
private DataApiClientImpl dataApiClientImpl;
@Autowired
private MockRestServiceServer mockRestServiceServer;
@Test
void testApiCall() {
mockRestServiceServer.expect(MockRestRequestMatchers.requestTo(OBJECT_ID_URI))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andExpect(MockRestRequestMatchers.queryParam("keyid", CoreMatchers.anything()))
.andExpect(MockRestRequestMatchers.queryParam("token", CoreMatchers.anything()))
.andRespond(MockRestResponseCreators.withSuccess("dummy", MediaType.APPLICATION_JSON));
String response = dataApiClientImpl.getItem("asdf12345", "test-obj-id");
Assertions.assertThat(response).isNotNull();
}
}
The error is
java.lang.AssertionError: Unexpected request expected:<http://localhost:8080/testBucketId/objects/test-obj-id> but was:<http://localhost:8080/testBucketId/objects/test-obj-id?token=asdf12345&keyid=testKeyId>
Expected :http://localhost:8080/testBucketId/objects/test-obj-id
Actual :http://localhost:8080/testBucketId/objects/test-obj-id?token=asdf12345&keyid=testKeyId
I can pass in a Matcher instead to requestTo()
method. But then what is the use of MockRestRequestMatchers.queryParam()
method, when the whole url with query params has to be verified using Matcher.
One option is to use startsWith Matcher MockRestRequestMatchers.requestTo(CoreMatchers.startsWith(OBJECT_ID_URI))
. But it is not same as exact match verification.
Tried with other overloaded versions of MockRestRequestMatchers.requestTo()
method. They all behave same.
Is there other better way to do exact endpoint path only match.
I did not include the test subject class code DataClientImpl
as I thought it is out of scope of the problem, but I can add here if need.