Jim
Jim

Reputation: 16022

how to mock a RestTemplate

I have setup a RestTemplate to collect data from an url.

My requirement is to test this code and more importantly the serializer, so given a piece of JSON how do I test that all the values come through to the instances of merchants correctly.

I don't know which serializer is used by RestTemplate to serialize JSON into objects.

RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>("", headers);
ResponseEntity<InboundMerchants> result = template.exchange(
        String.format("%s%s", uri, url),
        HttpMethod.GET,
        request,
        InboundMerchants.class);

InboundMerchants merchants = result.getBody();
return merchants == null
        ? Lists.newArrayList()
        : merchants.getMerchants();

Upvotes: 0

Views: 231

Answers (1)

Mounir Messaoudi
Mounir Messaoudi

Reputation: 373

For unit test you can use Mockito if you are using Spring, please check this tutorial: https://www.baeldung.com/spring-mock-rest-template

For integration tests (Your requirement i think) you can use both RestTemplate and MockMvc, please check this thread:

Difference between MockMvc and RestTemplate in integration tests

Upvotes: 1

Related Questions