Search code examples
javajunitjmockit

Mocking local object is not working - jmockit


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);

    }
}

Solution

  • 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));
        }