TheDarkLord
TheDarkLord

Reputation: 351

verifyNoMoreInteractions fails when iterating a collection of mocks

I have this code snippet that I want to unit test:

public void method(Set<Foo> fooList){
    for (Foo f : fooList) {
       EnumClass i = f.get();
    }
}

And I have this test code in Mockito:

Collection<Foo> mockFoos = Sets.newHashSet(mockFoo1, mockFoo2);
when(mockFoo1.get()).thenReturn(*some enum value*);
when(mockFoo2.get()).thenReturn(*some enum value*);
...
verifyNoMoreInteractions(mockFoos.toArray())

And for some reason the test fails, I also tried added logging and the mocks and the only recorded interactions are calls to get.

I dont think it matters but Foo extends from some other class.

Upvotes: 3

Views: 577

Answers (2)

TheDarkLord
TheDarkLord

Reputation: 351

Resolved it by using ignoreStubs, mockito seem to consider the "invocation" of get in when(mockFoo1.get()).thenReturn(*some enum value*); as an unstubbed invocation and thats why it failed, the solution was to use: verifyNoMoreInteractions(ignoreStubs(mockFoos.toArray()))

Upvotes: 1

Borislav Stoilov
Borislav Stoilov

Reputation: 3687

mockFoos.toArray() will create new object and mockito will work with it not your mockFoos collection.

According to the mockito documentation the last line should be verifyNoMoreInteractions(mockFoos)

Upvotes: 0

Related Questions