0

I want to mock the resttemplate call which is instansiated as local variable and exchange method invoked. I mocked using expectation but it invokes the actual method . Am I missing something . Please help me on this . Thanks in advance

public class ServiceController {
    public String callGetMethod (HttpServletRequest request){
        String url = request.getParameter("URL_TO_CALL");
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        return res.getBody();
    }
}

@RunWith(JMockit.class)
public class ServiceControllerTest {
    @Tested
    private ServiceController controller;
    @Test
    public void callGetMethod (@Mocked HttpServletRequest request, @Mocked RestTemplate restTemplate){
        new NonStrictExpectations() {
        {
            restTemplate.exchange(host,HttpMethod.GET, entity,String.class); returns (new ResponseEntity<String>("success" , HttpStatus.OK));
        }

        ResponseEntity<String> response = controller.callGetMethod(httpServletRequest);

    }
}
Abdul
  • 942
  • 2
  • 14
  • 32
  • Try to explicitly @Mock RestTemplate after defining class. Also try to instantiate Controller ocntroller = new Controller(); Think about name changing to that class Controller. – alxbxbx Aug 23 '17 at 09:04
  • I just gave a common name for controller and its not a actual name used in the code . Also its not my code to change the restTemplate object placement. – Abdul Aug 23 '17 at 09:08
  • You could check this guy's answer https://stackoverflow.com/questions/42406625/how-to-mock-resttemplate-in-java-spring – alxbxbx Aug 23 '17 at 09:26
  • above link wants to move the local method variable to global variable . I cant do it because its not my place to do it. – Abdul Aug 24 '17 at 09:26

1 Answers1

1

We need to mock the new RestTemplate() . So that it will assign mocked object restTemplate to method local variable .

@Mocked
RestTemplate restTemplate;

new NonStrictExpectations() {
    {
      new RestTemplate();
      result = restTemplate; 
      restTemplate.exchange(host, HttpMethod.GET, entity, String.class);
      returns(new ResponseEntity<String>("success", HttpStatus.OK));
    }
Abdul
  • 942
  • 2
  • 14
  • 32