Skip to content

mock resttemplate to test a service as restFul client

I have a service class, written in spring, with some methods.

One of this acts as a restful consumer like below:

HttpEntity request = new HttpEntity<>(getHeadersForRequest());
RestTemplate restTemplate = new RestTemplate();
String url = ENDPOINT_URL.concat(ENDPOINT_API1);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                                        .queryParam("param1", parameter1);
ReportModel infoModel = null;
try {
    infoModel =,
                    HttpMethod.GET, request, ReportModel.class).getBody();
} catch (HttpClientErrorException | HttpServerErrorException e){

I want to use Mockito to mock my service, but every method that interacts with restful server instance a new RestTemplate.

I’ve to create a static class to Inject it into my service?



One of the benefits from dependency injection is to be able to easily mock your dependencies. In your case it would be a lot easier to create a RestTemplate bean:

public RestTemplate restTemplate() {
    return new RestTemplate();

And in stead of using new RestTemplate() in your client you should use:

private RestTemplate restTemplate;

For the unit testing with Mockito you’ll have to mock the RestTemplate, for example by using:

public class ClientTest {
    private Client client;
    private RestTemplate restTemplate;

In this case Mockito will mock and inject the RestTemplate bean in your Client. If you don’t like mocking and injecting through reflection you can always go for a separate constructor or setter to inject the RestTemplate mock.

Now you can write a test like this:

verify(restTemplate).exchange(anyString(), eq(HttpMethod.GET), any(HttpModel.class), eq(ReportModel.class));

You’ll probably want to test more than that, but it gives you a basic idea.

User contributions licensed under: CC BY-SA
9 People found this is helpful