2017-08-23 40 views
0

我想模拟resttemplate调用,它被调用为本地变量和交换方法。我嘲笑使用期望,但它调用了实际的方法。我错过了什么。请帮助我。在此先感谢嘲笑本地对象无法正常工作 - jmockit

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

    } 
} 
+0

尝试显式@Mock RestTemplate定义类后。也尝试实例化控制器ocntroller = new Controller();考虑将名称更改为该类控制器。 – alxbxbx

+0

我只给了控制器的通用名称,而不是代码中使用的实际名称。也不是我的代码来改变restTemplate对象的位置。 – Abdul

+0

你可以检查这个人的回答https://stackoverflow.com/questions/42406625/how-to-mock-resttemplate-in-java-spring – alxbxbx

回答

0

我们需要模拟新的RestTemplate()。这样它会将模拟对象restTemplate分配给方法局部变量。

@Mocked 
RestTemplate restTemplate; 

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