3

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.

Community
  • 1
  • 1
Vikram
  • 2,042
  • 3
  • 14
  • 15
  • 3
    Does this help: http://stackoverflow.com/questions/6379308/testing-java-enhanced-for-behavior-with-mockito – Matthew S. Nov 15 '13 at 17:43
  • I guess you need mock iterator instead. Here is the [ref](http://stackoverflow.com/questions/6379308/testing-java-enhanced-for-behavior-with-mockito) – chenrui Nov 15 '13 at 18:13

4 Answers4

10

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

Rangi Lin
  • 9,303
  • 6
  • 45
  • 71
2

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.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
2

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");
}};
leojh
  • 7,160
  • 5
  • 28
  • 31
0

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

Aldian Fazrihady
  • 141
  • 1
  • 1
  • 6
  • 1
    please add the valuable content of the link in the answer, the link might be unreachable in the future. – Paizo Jan 05 '16 at 11:05