2013-10-30 45 views
6

我嘲笑之後也得到空指針異常。請找到我的項目結構。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代碼嘲笑。你能幫我解決這個問題嗎?

+0

您需要在您的應用注入模擬,否則當你調用listPets() – Morfic

+0

如何做到這一點App.petService將爲空? –

+0

你可以使用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

回答

5

NullPointerException是因爲在App中,petService在嘗試使用它之前沒有實例化。注入模擬,在應用中添加這個方法:在您的測試

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

然後,調用:

app.setPetService(petService); 

運行app.listPets();

9

之前,您還可以使用@InjectMocks註釋,這樣你不需要任何獲得者和制定者。只要確保你在你的註釋下課後你的測試用例下方添加,

@Before 
public void initMocks(){ 
    MockitoAnnotations.initMocks(this); 
}