10

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?

4

2 回答 2

10

您还可以使用@InjectMocks注释,这样您就不需要任何 getter 和 setter。只需确保在注释类后在测试用例中添加以下内容,

@Before
public void initMocks(){
    MockitoAnnotations.initMocks(this);
}
于 2014-09-30T10:03:45.503 回答
5

NullPointerException 是因为在 App 中,petService 在尝试使用它之前没有被实例化。要注入模拟,请在 App 中添加此方法:

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

然后在您的测试中,调用:

app.setPetService(petService);

跑步前app.listPets();

于 2013-10-30T17:11:55.063 回答