英文:
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'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're all set up with the mockito stuff, and now I'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: 'package.Wrapper' to 'package.Wrapper<T>'`
I read another suggestion somewhere that with Java 8, you'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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论