Peters_
Peters_

Reputation: 647

How to mock for each loop properly using Mockito?

I would like to test my method and I need to mock the vector of Items and Rows to go through each of them.

I prepared the result vector that I would like to get always when I call getRows() from Item class (within the test).

The problem is that the result of getRows method in test is always empty so it means that doReturn statement is not working correctly here.

Am I wrong with something?

class MyServiceTest {
@Mock
private Item mockedItem;

@Mock
private Row mockedRow;

@InjectMocks
@Spy
private MyService myService;

@Test
public void testMyMethod() {
    Vector<Row> rows = new Vector<Row>();
    Row row = new Row();
    rows.add(row);

    doReturn(rows).when(mockedItem).getRows();

    ...
    //some code to test the service

    }
}

class MyService {
    protected SomeObject myMethod(Vector<Item> items) {     
        for(Item item : items) {
            for(Row row : item.getRows()) {
               //cannot get here while debugging the test

               //some code
            }
        }
    ...
    }
}
class Item {
...
    public Vector<Row> getRows(){
       //return some vector of rows
    }
}

Upvotes: 0

Views: 10179

Answers (1)

davidxxx
davidxxx

Reputation: 131346

The @InjectMock is useless as the mocked vector is a parameter of the tested method, not a field of the class under test.
So you need to inject nothing.

What you need to do is creating a Vector of Item where each element is a mock with the expected behavior for getRows() : returning stubbed rows.

Here is a sample code :

// create stubbed rows
Vector<Row> rows = new Vector<Row>();
Row row = new Row();
rows.add(row);

// mock items Vector
Vector<Item> items = new Vector<>();
for (...){ // nb element to create
  Item mockedItem = Mockito.mock(Item.class);
  doReturn(rows).when(mockedItem).getRows();
  items.add(mockedItem);
}

Then invoke your tested method by passing the vector:

new MyService().myMethod(items);

Note that Vector is an old and flawed Collection.
User rather List and ArrayList as implementation if you don't need to handle race conditions.

Upvotes: 4

Related Questions