Mockito参数匹配器,用于匹配具有泛型的任何类型,不包括null。

huangapple go评论66阅读模式
英文:

Mockito argument matcher that matches any of a type with generics, excluding nulls

问题

让我们假设我有这样一个类

```java
public class Wrapper<T> {
    T data;
}

然后我有一个方法调用,就像这样:

public interface ThingDoer {
     <T> boolean doSomething(Wrapper<T> wrapper);
}

我想在测试中模拟掉它。假设我们已经用好了 Mockito 相关的设置,现在我正在尝试模拟这个方法调用

when(thingDoer.doSomething(any(Wrapper.class))).thenReturn(true);

然而,这会给我一个警告:Unchecked assignment: 'package.Wrapper' to 'package.Wrapper<T>'

我在某个地方看到另一个建议,使用 Java 8 时,应该使用 any() 而不是 any(Wrapper.class)。然而,通过阅读关于这两个方法的文档,any() 将接受 null 参数,而 any(Class) 将拒绝 null 参数,所以它们并不完全相同。有没有一种方法在不产生警告的情况下排除掉 null 值?


<details>
<summary>英文:</summary>

Lets say I&#39;ve got a class like this

public class Wrapper<T> {
T data;
}


And I have a method call like this:

public interface ThingDoer {
<T> boolean doSomething(Wrapper<T> wrapper)
}


which I want to mock out in a test. Lets say we&#39;re all set up with the mockito stuff, and now I&#39;m trying to mock out this method call

when(thingDoer.doSomething(any(Wrapper.class))).thenReturn(true);


However, this will give me a warning: `Unchecked assignment: &#39;package.Wrapper&#39; to &#39;package.Wrapper&lt;T&gt;&#39;`

I read another suggestion somewhere that with Java 8, you&#39;re supposed to use `any()` instead of `any(Wrapper.class)`. However, reading through the documentation on these two methods, `any()` will accept null arguments and `any(Class)` will reject null arguments, so they are not quite synonymous. Is there a way to exclude nulls without getting a warning?

</details>


# 答案1
**得分**: 1

使用 [`isNotNull()`](https://javadoc.io/static/org.mockito/mockito-core/3.3.3/org/mockito/ArgumentMatchers.html#isNotNull--) 作为匹配器。

```java
when(thingDoer.doSomething(isNotNull())).thenReturn(true);
英文:

Use isNotNull() as the matcher.

when(thingDoer.doSomething(isNotNull())).thenReturn(true);

huangapple
  • 本文由 发表于 2020年9月4日 03:56:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63730816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定