【问题标题】:Verifying a List of List argument in Mockito在 Mockito 中验证 List 参数列表
【发布时间】:2017-12-21 10:51:21
【问题描述】:

假设我有一个将List<List<MyObject>> 作为参数的方法:

public void myFunction(List<List<MyObject>> listOfList) {}

我知道我可以使用 anyList() 作为匹配器,例如

verify(myClass).myFunction(anyList());

但是,我收到了未经检查的分配警告。我不能使用这些匹配器中的任何一个,因为它们会产生编译错误:

// Fails - Expects just a single-layered List<MyObject>
verify(myClass).myFunction(anyListOf(MyObject.class));

// Fails - "no instance(s) of type variable(s) T exist so that List<T> conforms to Class<T>"
verify(myClass).myFunction(anyListOf(anyListOf(MyObject.class)));

那么我如何为List&lt;List&lt;T&gt;&gt; 类型的参数创建一个类型安全的匹配器?

【问题讨论】:

  • 不,据我所知不可能。这是一个普遍的问题。 Mockito 为许多泛型类型提供了预定义的匹配器。例如anyList()、anyMap() 或anyString()。但不适用于List&lt;List&gt;。因此您无法获得类型安全的匹配器

标签: android unit-testing testing mockito


【解决方案1】:

你可以使用 Matchers.any() 做一个类型安全的匹配器并用类型限定它:

Matchers.<List<List<MyObject>>>any()

【讨论】:

  • 有趣的是,在我的例子中,它可以缩短为 Matchers.any(),因为参数指的是一个具体的类。 "This inspection reports all calls to parametrized methods where explicit argument types can be omitted, since they will be unambiguously inferred by compiler. Such usages make code excessive and thus less readable."
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多