【问题标题】:Mockito Unit Test Case call is Ambiguous (Need to get it to not be ambiguous)Mockito 单元测试用例调用是模棱两可的(需要让它不模棱两可)
【发布时间】:2016-07-29 17:14:43
【问题描述】:

我应该如何编写以下 Mockito Matchers 以使调用不模棱两可?

我试图在我的代码中模拟的实际函数调用是:

//Variables
String url = http://theServer:8080/oath2-v1/token;
HttpEntity<String> request = new HttpEntity<String>("name=value",headers);

//Method call I am trying to mock using Mockito
response=cmsRestTemplate.exchange(url, HttpMethod.POST, request, DdsOAuthToken.class);

下面是我的单元测试用例中的一个 sn-p。它包含以下模拟上述调用的模拟调用,但不幸的是编译器发现它不明确并且不会编译。

//From the Unit Test...
when(restTemplate.exchange(
    Matchers.anyString(),
    Matchers.any(HttpMethod.class),
    Matchers.any(HttpEntity.class),
    Matchers.<Class<DdsOAuthToken>>any(),
    Matchers.anyVararg()).thenReturn(response));

我得到的错误如下:

The method exchange(String, HttpMethod, HttpEntity<?>, Class<DdsOAuthToken>, Object[]) is ambiguous for the type RestTemplate

这是一个 Spring RestTemplate api 调用。具体来说,它发现模棱两可的 2 个 api 调用是以下 2 个调用:

1. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)

2. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables)

我试图模拟上面的#1。但是 Java 编译器无法判断我是在尝试调用 #1 还是 #2。究竟我应该如何编写 Mockito 匹配器,以便它知道我想要上面的 #1 而不是 #2?

【问题讨论】:

    标签: java unit-testing compiler-errors mockito matcher


    【解决方案1】:

    您必须在 vararg 参数中添加演员 (Object[])。这可能与anyVararg 方法的声明有关。但我不确定。所以你的代码应该是:

    //From the Unit Test...
    when(restTemplate.exchange(
        Matchers.anyString(),
        Matchers.any(HttpMethod.class),
        Matchers.any(HttpEntity.class),
        Matchers.<Class<DdsOAuthToken>>any(),
        (Object[]) Matchers.anyVararg()).thenReturn(response));
    

    【讨论】:

      【解决方案2】:

      通常,模拟您无法控制的类是一个错误的决定。 Spring 框架带有实用程序类,可帮助您测试框架的使用情况。

      例如MockRestServiceServer 是一个虚拟服务器,它将为RestTemplate 实例提供有效响应,因此您无需模拟它。

      An example from docs

      RestTemplate restTemplate = new RestTemplate();
      
      MockRestServiceServer mockServer =  MockRestServiceServer.createServer(restTemplate);
      
      mockServer.expect(requestTo("/greeting"))
            .andRespond(withSuccess("Hello world", "text/plain"));
      
      // use RestTemplate ...
      

      【讨论】:

        猜你喜欢
        • 2017-12-03
        • 2014-09-28
        • 1970-01-01
        • 2019-06-07
        • 1970-01-01
        • 2016-04-18
        • 2011-09-07
        • 2010-11-18
        • 2019-09-13
        相关资源
        最近更新 更多