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

The following code is copied from the above link:

1 comment:

  1. I get this error when executing this style.

    when() requires an argument which has to be 'a method call on a mock'.
    For example:

    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.