Nobwyn
Nobwyn

Reputation: 8685

Mockito: how to expect an iterator to be equal?

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

Upvotes: 2

Views: 3917

Answers (3)

csauve
csauve

Reputation: 6263

I've implemented an IterableMatcher<T>. This includes a static method elemEq that will create one of these for you.

For example:

doReturn(result).when(mock).method(elemEq(expected));

https://gist.github.com/collinsauve/1fcf924cdcced40e0bee

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691735

You could use

when(myMock.doSomething(eq("some string"), argThat(new IsIteratorOfList(aList))))

where IsIteratorOfList is 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 (aList in this case).

The matcher could be even simpler and just check the first element, or the number of elements, or anything you want.

Upvotes: 1

kan
kan

Reputation: 28951

You always could make your own implementation of the Iterator interface.

Upvotes: 0

Related Questions