Home » Android » java – mockito – mocking an interface – throwing NullPointerException

java – mockito – mocking an interface – throwing NullPointerException

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&Answers:

NullPointerException is because, in App, petService isn’t instantiated before trying to use it. To inject the mock, in App, add this method:

public void setPetService(PetService petService){
    this.petService = petService;
}

Then in your test, call:

app.setPetService(petService);

before running app.listPets();

Answer:

You can also use @InjectMocks annotation, that way you wont need any getters and setters. Just make sure you add below in your test case after annotating your class,

@Before
public void initMocks(){
    MockitoAnnotations.initMocks(this);
}