Wednesday, May 6, 2015

How to mock a for loop using mockito

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:

2 comments:

  1. I get this error when executing this style.

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

    ReplyDelete
  2. An easy way to do your test can be something like this:
    public void setUp() {

    List mockfruitList=new ArrayList<>();
    mockfruitList.add(Arrays.asList(“Apple”,”Banana”,”Pear”));
    fruits=mock(Collection.class);
    when(fruits.iterator()).thenReturn(mockfruitList.iterator());
    }

    ReplyDelete