Mockito - Mocking Interface - Throwing NullPointerException

I get a null pointer exception after bullying. 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, which means I have a service interface, but not an actual implementation. To test the listPets () method, I clearly know that its using the service to get a list of pets. But my intention here is to test the listPets () method of the App class, so I'm trying to make fun of the service interface.

The listPets () method of the App class using the pet service. Therefore, I am mocking this part using mockito.

  Mockito.when(petService.listPets()).thenReturn(list); 

But when the unit test runs, perService.listPets () throws a NullPointerException , which I mocked at this Mockito.when code. Could you help me with this?

+6
source share
2 answers

A NullPointerException is because the petService application is not created in the application before trying to use it. To add a layout in the application, add this method:

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

Then in your test call:

 app.setPetService(petService); 

before running app.listPets();

+5
source

You can also use the @InjectMocks annotation, so you don't need any getters and setters. Just make sure you add below to your test case after annotating your class,

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

Source: https://habr.com/ru/post/957059/


All Articles