我也在模拟后得到空指针异常.请找到我的项目结构.
//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 listPets();
}
// a client code using the PetService to list Pets
public class App {
PetService petService;
public void listPets() {
// TODO Auto-generated method stub
List 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 listPets = app.listPets();
Pet[] pet = new Dog[]{new Dog(1,"puppy")};
List list = Arrays.asList(pet);
Mockito.when(petService.listPets()).thenReturn(list);
app.listPets();
}
}
我在这里尝试使用TDD,意味着我已经编写了服务接口,但不是实际的实现.为了测试listPets()方法,我清楚地知道它使用该服务来获取宠物列表.但我的意图是在这里测试App类的listPets()方法,因此我试图模拟服务接口.
App类的listPets()方法使用该服务来获取宠物.所以我用mockito嘲笑那个部分.
Mockito.when(petService.listPets()).thenReturn(list);
但是当单元测试运行时,perService.listPets()抛出NullPointerException,我已经使用上面的Mockito.when代码进行了模拟.你能帮帮我吗?