Today when I tried to use mockito to write unit test cases, I found I need to mock the for loop operation. Then I found the solution from here in stackoverflow: the basic idea is to mock the iterator class and collection class, and base on your situation, you need to set the expectation of iterator.hasNext() and iterator.next() method.
The following code is copied from the above link:
I get this error when executing this style.
ReplyDeleteorg.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
An easy way to do your test can be something like this:
ReplyDeletepublic void setUp() {
List mockfruitList=new ArrayList<>();
mockfruitList.add(Arrays.asList(“Apple”,”Banana”,”Pear”));
fruits=mock(Collection.class);
when(fruits.iterator()).thenReturn(mockfruitList.iterator());
}