RestClient does work with MockRestServiceServer.
Consider the following component:
@Component
public class MyClient {
private final RestClient restClient;
// it's important to inject the RestClient.Builder, as it will be configured
// by the @RestClientTest to interact with the MockRestServiceServer
public MyClient(RestClient.Builder builder) {
this.restClient = builder.build();
}
public String doSomething() {
// do whatever you want to do as a client
return restClient.get().uri("/path/resource").retrieve().body(String.class);
}
}
Then your integration test can look as easy as this:
@RestClientTest(MyClient.class)
class MyClientIT {
@Autowired
private MockRestServiceServer server;
@Autowired
private MyClient myClient;
@Test
void testSomething() {
server.expect(requestTo("/path/resource")).andRespond(withSuccess("success", MediaType.TEXT_PLAIN));
var result = myClient.doSomething();
assertThat(result).isEqualTo("success");
server.verify(); // verify the server received the expected request
}
}
If you want to customize the RestClient (e.g. for reuse), make sure to build it using an injected RestClient.Builder. For example, if you have a configuration like that:
@Configuration
public class MyClientConfiguration {
// it's important to use the injected RestClient.Builder, not build a new one!
@Bean
public RestClient customizedRestClient(RestClient.Builder builder) {
// customize it, for example
return builder.baseUrl("https://remote-server.com/").build();
}
}
Then ensure to use the RestClient in your component:
@Component
public class MyClient {
private final RestClient restClient;
public MyClient(RestClient customizedRestClient) {
this.restClient = customizedRestClient;
}
public String doSomething() {
// do whatever you want to do as a client
return restClient.get().uri("/path/resource").retrieve().body(String.class);
}
}
Last, you need to import the configuration in your integration test so that MyClient can be autowired. Please note that the RestClient.Builder is provided by the RestClientTest when building the customizedRestClient bean. Also, the test needs to adapt to the base url.
@RestClientTest({ MyClient.class, MyClientConfiguration.class })
class MyClientIT {
@Autowired
private MockRestServiceServer server;
@Autowired
private MyClient myClient;
@Test
void testSomething() {
server.expect(requestTo("https://remote-server.com/path/resource"))
.andRespond(withSuccess("success", MediaType.TEXT_PLAIN));
var result = myClient.doSomething();
assertThat(result).isEqualTo("success");
server.verify(); // verify the server received the expected request
}
}