Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito - mocking an interface - throwing NullPointerException

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?

like image 471
Arun Kamalanathan Avatar asked Oct 30 '13 16:10

Arun Kamalanathan


2 Answers

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);
}
like image 148
Srinivas Pasupulate Avatar answered Nov 10 '22 02:11

Srinivas Pasupulate


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();

like image 21
Chris Avatar answered Nov 10 '22 03:11

Chris