mockito - mocking an interface - throwing NullPointerException

若如初见. 提交于 2020-01-22 18:49:04

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/19689061/mockito-mocking-an-interface-throwing-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!