我嘲笑之後也得到空指針異常。請找到我的項目結構。mockito - 嘲諷一個接口 - 拋出NullPointerException
//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代碼嘲笑。你能幫我解決這個問題嗎?
您需要在您的應用注入模擬,否則當你調用listPets() – Morfic
如何做到這一點App.petService將爲空? –
你可以使用Mock和InjectMocks註釋 - 更多細節在這裏http://stackoverflow.com/questions/19580197/injection-of-a-mock-object-into-an-object-to-be-tested-declared- as-a-field-in-th/19610215#19610215 – macias