【问题标题】:Mockito Matcher for Integer... parameterMockito Matcher for Integer... 参数
【发布时间】:2016-04-25 16:19:49
【问题描述】:

此方法签名中第二个参数的正确 Mockito 匹配器是什么:

List<Something> findSomething(Object o, Integer... ids);

我尝试了以下匹配器:

when(findSomething(any(), anyInt())).thenReturn(listOfSomething);
when(findSomething(any(), any())).thenReturn(listOfSomething);

但是 Mockito 没有为我创建代理,返回的 List 是空的。

【问题讨论】:

    标签: java unit-testing mocking mockito


    【解决方案1】:

    像这样使用anyVararg()

    Application application = mock(Application.class);
    List<Application> aps = Collections.singletonList(new Application());
    
    when(application.findSomething(any(), anyVararg())).thenReturn(aps);
    
    System.out.println(application.findSomething("foo").size());
    System.out.println(application.findSomething("bar", 17).size());
    System.out.println(application.findSomething(new Object(), 17, 18, 19, 20).size());
    

    输出:

    1
    1
    1
    

    【讨论】:

      【解决方案2】:

      Integer... 是定义Integers 数组之上的语法糖。所以模拟它的正确方法是:

      when(findSomething(any(), any(Integer[].class))).thenReturn(listOfSomething);
      

      【讨论】:

      • 这导致编译器错误:SomethingService 类型中的方法 findSomething(Object, Integer...) 不适用于参数 (Object, Matcher)
      猜你喜欢
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2011-07-09
      • 2023-03-03
      • 2022-09-23
      相关资源
      最近更新 更多