Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: mocking an arraylist that will be looped in a for loop

Tags:

I have a method under test that contains the following snippet:

private void buildChainCode(List<TracedPath> lines){     for(TracedPath path : lines){         /.../     } } 

My unit test code looks like this:

public class ChainCodeUnitTest extends TestCase {      private @Mock List<TracedPath> listOfPaths;     private @Mock TracedPath tracedPath;      protected void setUp() throws Exception {         super.setUp();         MockitoAnnotations.initMocks(this);     }      public void testGetCode() {         when(listOfPaths.get(anyInt())).thenReturn(tracedPath);          ChainCode cc = new ChainCode();         cc.getCode(listOfPaths);          /.../     } } 

The problem is, that while running the test, the test code never enters the for loop. What when conditions should I specify, so that the for loop would be entered? Currently I have specified when(listOfPaths.get(anyInt())).thenReturn(tracedPath), but I guess it is never used.

like image 228
Rebane Lumes Avatar asked Aug 28 '13 08:08

Rebane Lumes


1 Answers

Your problem is that when you use a collection in a for-each loop, its iterator() method gets called; and you haven't stubbed that particular method.

Instead of mocking the list, I strongly recommend you just pass a real list, where the elements are just your mocked TracedPath, as many times as you want it. Something like

listOfPaths = Arrays.asList(mockTracedPath, mockTracedPath, mockTracedPath); 
like image 133
Dawood ibn Kareem Avatar answered Oct 21 '22 16:10

Dawood ibn Kareem