的Mockito - 嘲讽的接口 - 抛出NullPointerException异常 [英] 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();
}
}
我想在这里使用TDD,意味着我有写的服务接口,但没有实际执行。要测试listPets()方法中,我清楚地知道它使用服务来获得宠物列表。但在这里我打算测试listPets App类的()方法,所以我试图嘲弄服务接口。
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.
使用该服务,以获得宠物App类的listPets()方法。因此我使用嘲讽的Mockito那部分。
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);
但是,当单元测试运行时,perService.listPets()抛出的 NullPointerException异常这是我使用上述 Mockito.when code嘲笑。你能帮我在这?
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?
推荐答案
NullPointerException异常是因为,在应用程序,petService是不是想使用它之前实例化。注入模拟,在应用中添加这个方法:
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);
运行前 app.listPets();
这篇关于的Mockito - 嘲讽的接口 - 抛出NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!