Mockito: Verifying with generic parameters

后端 未结 4 990
北海茫月
北海茫月 2020-12-02 19:34

With Mockito I can do the following:

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

But how do I write this if process takes

相关标签:
4条回答
  • 2020-12-02 20:08

    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());
    
    0 讨论(0)
  • 2020-12-02 20:11

    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.

    0 讨论(0)
  • 2020-12-02 20:26

    Try :

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

    Since version 1.8 Mockito introduces

    public static <T> Collection<T> anyCollectionOf(Class<T> clazz);
    
    0 讨论(0)
  • 2020-12-02 20:34

    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.

    0 讨论(0)
提交回复
热议问题