I have a method, which accept a string and an iterator:
public int doSomething(String str, Iterator<String> itr)
I am trying to mock a class, where this method is, so it would return me integer, depending on passed arguments. How can I call Mockito’s when() so it expects passed iterator to be “equal” to the one I specify? As the passed iterator is build somewhere dynamically in system, I cannot use the same instance of it in when(), so I can only make a copy of it as my expectation:
List<String> aList = new ArrayList<String>();
aList.add("one");
aList.add("two");
MyClass myMock = Mockito.mock(MyClass.class);
I have tried following, and none of them seems to work:
Mockito.when(myMock.doSomething("some string", aList.iterator())).thenReturn(10);
Mockito.when(myMock.doSomething(Matchers.eq("some string"), Matchers.eq(aList.iterator()))).thenReturn(10);
I only succeeded with using anyObject():
Mockito.when(myMock.doSomething(Matchers.eq("some string"), Matchers.anyObject())).thenReturn(10);
but then of course I cannot set different results, depending on what is in iterator…
You could use
where
IsIteratorOfListis a subclass of ArgumentMatcher which checks that when the given iterator’selements are all added to a new list, this new list equals the list passed in the constructor (aListin this case).The matcher could be even simpler and just check the first element, or the number of elements, or anything you want.