Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = restTemplate.exchange(builder.toUriString(),
                    HttpMethod.GET, request, ReportModel.class).getBody();
} catch (HttpClientErrorException | HttpServerErrorException e){
    e.printStackTrace();
}

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?

like image 996
Claudio Pomo Avatar asked Jul 04 '16 11:07

Claudio Pomo


1 Answers

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:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

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

@Autowired
private RestTemplate restTemplate;

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

@RunWith(MockitoJUnitRunner.class)
public class ClientTest {
    @InjectMocks
    private Client client;
    @Mock
    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:

client.doStuff();
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.

like image 192
g00glen00b Avatar answered Sep 29 '22 11:09

g00glen00b