Mockito: Verifying with generic parameters

2019-01-10 21:50发布

With Mockito I can do the following:

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

But how do I write this if process takes a Collection<Person> instead? Can't figure out how to write it correctly. Just getting syntax errors...

4条回答
唯我独甜
2楼-- · 2019-01-10 22:39

Try :

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

Since version 1.8 Mockito introduces

public static <T> Collection<T> anyCollectionOf(Class<T> clazz);
查看更多
3楼-- · 2019-01-10 22:42

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. 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.

查看更多
小情绪 Triste *
4楼-- · 2019-01-10 22:43

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());
查看更多
该账号已被封号
5楼-- · 2019-01-10 22:44

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.

查看更多
登录 后发表回答