【发布时间】:2013-10-30 16:52:53
【问题描述】:
我在模拟后也得到空指针异常。请找到我的项目结构。
//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() 方法,我清楚地知道它使用服务来获取宠物列表。但我在这里的目的是测试 App 类的 listPets() 方法,因此我试图模拟服务接口。
App 类的 listPets() 方法使用服务获取宠物。因此,我使用 mockito 来模拟那部分。
Mockito.when(petService.listPets()).thenReturn(list);
但是当单元测试正在运行时,perService.listPets() 抛出 NullPointerException 我使用上面的 Mockito.when 代码进行了模拟。你能帮我解决这个问题吗?
【问题讨论】:
-
你需要在你的App中注入mock,否则调用listPets()时App.petService会为null
-
你可以使用 Mock 和 InjectMocks 注释 - 更多细节在这里stackoverflow.com/questions/19580197/…
-
Chris 回答的最简单的方法是构造函数/设置器,但您也可以使用 Mockito 的 @InjectMocks:docs.mockito.googlecode.com/hg/latest/org/mockito/…。首先阅读 Mockito 文档可能是个好主意,因为它很好地解释了事情是如何工作的。