0

I have a resttemplatebuilder in my resttemplate service as

restTemplate = restTemplateBuilder
                   .errorHandler(myResponseErrorHandler)
                   .build();
ResponseEntity<String> result = restTemplate.exchange(builder.buildAndExpand(urlParams).toUri(), 
                    HttpMethod.GET, requestEntity, String.class);

i have written a junit using mockito, i am mocking the resttemplate like below:

Mockito.when(restTemplate.exchange(builder.buildAndExpand(urlParams).toUri(), HttpMethod.GET, requestEntity, String.class)).thenReturn(new ResponseEntity<String>(details.toString(),HttpStatus.OK));

when i run my junit, i am keep on getting null pointer exception at below step in my source code service

restTemplate = restTemplateBuilder .errorHandler(myResponseErrorHandler)

can anyone help me to understand the problem?

Manju
  • 21
  • 2
  • `RestTemplate` is not good example for mock. Your problem because between calling `exchange` and returning value inside `RestTemplate` calling a lot of inner methods which you cannot mocks. Just run debug in your ide and go inside method `exchange` – borino Apr 14 '20 at 08:39
  • thank you for the response, do you suggest any other framework to handle this? – Manju Apr 15 '20 at 11:31
  • It depends of your test requirements. Looks like you works with Spring, it has their own tests mocks, with work perfectly and has good documentation and a lot of example. [Spring Test](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/testing.html#testing) – borino Apr 16 '20 at 06:32
  • @Manju , you could use [`@RestClientTest`](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/client/RestClientTest.html) for the tests. I can share a sample code if required. – R.G Apr 22 '20 at 04:39
  • @R.G yeah. please share it. actually i tried that as well. i was facing another issue, please refer https://stackoverflow.com/questions/61237686/unable-to-mock-the-resttemplate-call-using-restclienttest/61237895#61237895 – Manju Apr 23 '20 at 05:45
  • @Manju , I have commented the question with my observations. Please try the same. I will convert it to answer if that works. Let me know – R.G Apr 23 '20 at 06:00

0 Answers0