【问题标题】:Mocking local object is not working - jmockit模拟本地对象不起作用 - jmockit
【发布时间】:2017-08-23 09:00:22
【问题描述】:

我想模拟作为局部变量实例化的 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);

    }
}

【问题讨论】:

  • 在定义类后尝试显式地@Mock RestTemplate。也尝试实例化控制器 ocntroller = new Controller();考虑将名称更改为该类 Controller。
  • 我只是为控制器提供了一个通用名称,而不是代码中使用的实际名称。这也不是我更改 restTemplate 对象位置的代码。
  • 你可以查看这个人的答案stackoverflow.com/questions/42406625/…
  • 以上链接想要将本地方法变量移动到全局变量。我不能这样做,因为它不是我做的地方。

标签: java junit jmockit


【解决方案1】:

我们需要模拟新的 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));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多