Vikram
Vikram

Reputation: 2072

How to mock a For Loop using Mockito

I'm a newbie to mockito. My question is how can I mock a for loop using Mockito?

For Eg: This is the main Class:

import java.util.HashSet;
import java.util.Set;

    public class stringConcatination {

        public static void main(String[] args) {
            Set<String> stringSet = new HashSet();
            stringSet.add("Robert");
            stringSet.add("Jim");
            for (String s:stringSet) {
                s = "hi " + s;
            }
        }

}

This is the Test Class:

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;
import static org.mockito.Mockito.mock;

public class stringConcatinationTest {

    @Test
    public void testMain() {
        Set mockSet = mock(HashSet.class);
        // --  How to mock For Loop --
    }

}

I saw this related question. But I couldn't understand, how a for loop can be mocked.

Upvotes: 4

Views: 30568

Answers (4)

Aldian Fazrihady
Aldian Fazrihady

Reputation: 149

There is a feature in Mockito that can handle method call mocking inside iteration block. This is clearly explained at http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#stubbing_consecutive_calls

Upvotes: 0

leojh
leojh

Reputation: 7712

Also, you may use a Spy to deal with the real implementation vs. a mock. For collections, in particular, this may be a better approach then mocking them.

@Spy
private Set<String> mySet = new HashSet<String>()
{{
    add("john");
    add("jane");
}};

Upvotes: 2

Jeff Bowman
Jeff Bowman

Reputation: 95754

It is almost always a better idea to use real collections, such as ArrayList for a List implementation or HashSet for a Set implementation. Reserve your use of Mockito for collaborators that interact with external services or that have side effects, or that calculate hard-to-predict values, or that don't exist when you write your system under test. Collections in particular fail all three of these conditions.

To test a for loop, extract it to a method that takes a Collection or Iterable, and then create a List in your test to pass in. Your code will wind up more reliable and easier to follow because of it.

Upvotes: 2

Rangi Lin
Rangi Lin

Reputation: 9461

Since the for loop is just the syntax sugar of iterator() loop, you could just stub the method and return the mocked Iterator instance

Upvotes: 11

Related Questions