我想模拟resttemplate调用,该调用是作为局部变量和调用的交换方法实现的。我嘲笑使用期望,但它调用实际的方法。我错过了什么。请帮帮我。提前致谢
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 :(得分: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));
}