I am getting null pointer exception after mocking also. Please find my project structure.
//this is the pet interface
public interface Pet{
}
// An implementation of Pet
public class Dog extends Pet{
int id,
int petName;
}
// This is the Service Interface
public interface PetService {
List<Pet> listPets();
}
// a client code using the PetService to list Pets
public class App {
PetService petService;
public void listPets() {
// TODO Auto-generated method stub
List<Pet> listPets = petService.listPets();
for (Pet pet : listPets) {
System.out.println(pet);
}
}
}
// This is a unit test class using mockito
public class AppTest extends TestCase {
App app = new App();
PetService petService = Mockito.mock(PetService.class);
public void testListPets(){
//List<Pet> listPets = app.listPets();
Pet[] pet = new Dog[]{new Dog(1,"puppy")};
List<Pet> list = Arrays.asList(pet);
Mockito.when(petService.listPets()).thenReturn(list);
app.listPets();
}
}
I am trying to use TDD here, Means I have the service interface written, But not the actual implementation. To test the listPets() method, I clearly knows that its using the service to get the list of pets. But my intention here to test the listPets() method of the App class, Therefore I am trying to mock the service interface.
The listPets() method of the App class using the service to get the pets. Therefore I am mocking that part using mockito.
Mockito.when(petService.listPets()).thenReturn(list);
But when the unit test is running , perService.listPets() throwing NullPointerException which I have mocked using the above Mockito.when code. Could you please help me on this?