Reputation: 884
I have a method that return the list of vehicles. Like this:
public List<Vehicle> getVehicles() {
List<Vehicle> vehicles=vehicleDAO.getAllVehicles();
for (Vehicle v : vehicles){//NullPointerException
//some bussines logic...
}
return vehicles;
}
And here is my test:
@Test
public void testShowVehicles() {
when(vehicleDAO.getAllVehicles()).thenReturn(listVehiclesMock);
List<Vehicle> vehicles= service.getVehicles();//NullPointerException
assertEquals(listVehicleMock, vehicles);
}
When I run it I get NullPointerException because Vehicle does not exists. When I have old fashion for loop it passes the test, but now I replaced with forEach loop I get error in test. So how would I mock the object Vehicle?
Upvotes: 0
Views: 1123
Reputation: 3847
For each loop uses iterator()
method of the given Iterable
. An iterator obtained that way is then used to iterate over the collection. Unfortunately, this method of the mocked list returns null, which causes NullPointerException
. To use for each loop syntax you have to bind iterator()
method to result as well.
Upvotes: 2