2017-03-02 142 views
1

我正在嘗試編寫Mockito測試用例來獲取plantIDs並執行一些處理。 我也加了測試用例。使用Mockito嘲笑

這是我的測試案例

@RunWith(MockitoJUnitRunner.class) 
public class PlantDetailsServiceTest { 
    @InjectMocks PlantDetailsService service; 
    @Mock PlantDetailsHelper helperMock; 
    @Mock HttpURLConnection conn; 
    @Mock BufferedReader buf; 
    @Mock InputStream input; 
    @Mock InputStreamReader ir; 
    @Mock JSONObject json; 
    @Mock JSONArray arr; 
    @Mock List<String> plantResult; 


    @Test 
    public void TestGetPlantDetails() throws Exception 
    { 
     String plantID1= "23"; 

     List<String> plantResult = new ArrayList<String>(); 
     plantResult.add(plantID1); 
     Mockito.when(helperMock.getPlantIds()).thenReturn(plantResult); 
     URL url = new URL("**********/23"); 
     conn=(HttpURLConnection)url.openConnection(); 
     Mockito.when((HttpURLConnection)url.openConnection()).thenReturn(conn); 
     Mockito.when(conn.getResponseCode()).thenReturn(200); 
     input=conn.getInputStream(); 
     Mockito.when(conn.getInputStream()).thenReturn(input); 
     ir=new InputStreamReader(input); 
     Mockito.when(new InputStreamReader((conn.getInputStream()))).thenReturn(ir); 
     buf=new BufferedReader(ir); 
     Mockito.when(new BufferedReader(new InputStreamReader((conn.getInputStream())))).thenReturn(buf); 
     String output=buf.readLine(); 
     Mockito.when(buf.readLine()).thenReturn(output); 
     json=new JSONObject(output); 
     Mockito.when(new JSONObject(output)).thenReturn(json); 
     arr=json.getJSONArray("Data"); 
     Mockito.when(json.getJSONArray("Data")).thenReturn(arr); 
     assertThat(output,is(notNullValue())); 
     List<PlantDetailsDTO> plantDetailsList=new ArrayList<PlantDetailsDTO>(); 
     plantDetailsList=service.getPlantDetails(); 

    } 
} 

這將引發一個錯誤在我讀線InputStream()。我無法打開連接,因爲URL可能是最後一類。我也在openConnection()行中出錯。缺少方法調用。

+0

當你得到錯誤時,你的'helperMock'對象是否爲null? –

+0

空指針異常在com.test.PlantDetailsS​​erviceTest.TestGetPlantDetails(PlantDetailsS​​erviceTest.java:57) – Rindha

回答

1

我想你已經忘記了添加的兩個配置細節這將使註釋嘲諷一個:

@RunWith(MockitoJUnitRunner.class) 
public class PlantDetailsServiceTest { 

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

沒有這些,的Mockito不實例化@模擬的,因此你得到空指針異常。

+0

謝謝你它的工作,但探討新的問題。我可以發佈代碼嗎? – Rindha

+0

繼續..讓我們看看 –

+1

m8 ..該方法尚未準備好進行單元測試..甚至沒有關閉。你需要做的是重構它,並創建一些專門用於執行算法某些部分的輔助類。然後你會單元測試這些類的小公共方法。如果你現在試着測試這種方法,即使這是可能的,沒有人會理解這些測試,並且將來這些測試將被忽略。我知道重構是痛苦的,但這是測試像這樣的遺留代碼的唯一方法。 –