模拟本地对象不起作用 - jmockit
Mocking local object is not working - jmockit
我想模拟实例化为局部变量并调用交换方法的 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);
}
}
我们需要模拟新的 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));
}
我想模拟实例化为局部变量并调用交换方法的 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);
}
}
我们需要模拟新的 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));
}