Java <T> 的 Mockito.any()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30479646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito.any() for <T>
提问by Rajesh Kolhapure
I want to mock a method with signature as:
我想模拟一个带有签名的方法:
public <T> T documentToPojo(Document mongoDoc, Class<T> clazz)
I mock it as below:
我嘲笑它如下:
Mockito.when(mongoUtil.documentToPojo(Mockito.any(Document.class), Mockito.any(WorkItemDTO.class)))
But I get error as:
但我得到的错误是:
The method documentToPojo(Document, Class<T>)
in the type MongoUtil
is not applicable for the arguments (Document, WorkItemDTO)
documentToPojo(Document, Class<T>)
类型中的方法MongoUtil
不适用于参数(Document, WorkItemDTO)
Is there any method in Mockito which will help me mock for T?
Mockito 中是否有任何方法可以帮助我模拟 T?
采纳答案by Jeff Bowman
Note that documentToPojo
takes a Classas its second argument. any(Foo.class)
returns an argument of type Foo
, not of type Class<Foo>
, whereas eq(WorkItemDTO.class)
should return a Class<WorkItemDTO>
as expected. I'd do it this way:
请注意,documentToPojo
将Class作为其第二个参数。any(Foo.class)
返回 type 的参数,而Foo
不是 type Class<Foo>
,而eq(WorkItemDTO.class)
应该Class<WorkItemDTO>
按预期返回 a 。我会这样做:
when(mongoUtil.documentToPojo(
Mockito.any(Document.class),
Mockito.eq(WorkItemDTO.class))).thenReturn(...);
回答by Anders R. Bystrup
You can match a generic Class<T>
argument using simply any( Class.class )
, eg.:
您可以Class<T>
使用 simple匹配泛型参数any( Class.class )
,例如:
Mockito.when( mongoUtil.documentToPojo( Mockito.any( Document.class ),
Mockito.any( Class.class ) ) );
Cheers,
干杯,
回答by Collin Krawll
You can do it using ArgumentMatchers.any() qualified with the type, like so:
您可以使用带有类型限定的 ArgumentMatchers.any() 来完成,如下所示:
Mockito.when(
mongoUtil.documentToPojo(
Mockito.any(Document.class),
ArgumentMatchers.<Class<WorkItemDTO>>any()
)
).thenReturn(...);