我正在嘗試編寫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()
行中出錯。缺少方法調用。
當你得到錯誤時,你的'helperMock'對象是否爲null? –
空指針異常在com.test.PlantDetailsServiceTest.TestGetPlantDetails(PlantDetailsServiceTest.java:57) – Rindha