简体   繁体   English

Mockito:使用通用参数进行验证

[英]Mockito: Verifying with generic parameters

With Mockito I can do the following:使用 Mockito,我可以执行以下操作:

verify(someService).process(any(Person.class));

But how do I write this if process takes a Collection<Person> instead?但是,如果process使用Collection<Person>代替,我该怎么写呢? Can't figure out how to write it correctly.无法弄清楚如何正确编写它。 Just getting syntax errors...刚刚收到语法错误...

Try: 尝试:

verify(someService).process(Matchers.<Collection<Person>>any());

Actually, IntelliJ automatically suggested this fix when I typed any() ... Unfortunately you cannot use static import in this case. 实际上,当我输入any()时,IntelliJ会自动建议这个修复...不幸的是,在这种情况下你不能使用静态导入。

Try : 试试:

verify(someService).process(anyCollectionOf(Person.class));

Since version 1.8 Mockito introduces 1.8版Mockito推出以来

public static <T> Collection<T> anyCollectionOf(Class<T> clazz);

if you use a own method, you can even use static import: 如果您使用自己的方法,您甚至可以使用静态导入:

private Collection<Person> anyPersonCollection() {
    return any();
}

Then you can use 然后你可以使用

verify(someService).process(anyPersonCollection());

As an alternative to the accepted answer you can try:作为已接受答案的替代方案,您可以尝试:

verify(someService).process(Mockito.<SomeGenericClass<Person>>any());

Where I used org.mockito.Mockito instead of Matchers .当我用org.mockito.Mockito代替Matchers

You can't express this because of type erasure. 由于类型擦除,你无法表达这一点。 Even if you could express it in code, Mockito had no chance to check it at runtime. 即使您可以在代码中表达它,Mockito也没有机会在运行时检查它。 You could create an interface like 你可以创建一个像这样的界面

interface PersonCollection extends Collection<Person> { /* nothing */ }

instead and use this throughout your code. 而是在整个代码中使用它。

Edit: I was wrong, Mockito has anyCollectionOf(..) which is what you want. 编辑:我错了,Mockito有anyCollectionOf(..)这就是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM