0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you give some tips how would I bind iterator() to the test.
Instead of returning a mocked list from a mock object, it might be easier returning an actual list with a single Vehicle object. This way, you won't have to write additional when clauses and avoid NullPointerException within your business logic.
Is this ok that I return actual list instead of mocked list?
Yes, it's fine to return an actual list instead of a mock. There's nothing about the List class that needs to be faked in order to test your class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.