我已經通過StackOverflow搜索了相同類型的問題,並檢查了每個響應,但仍然面臨此問題。我測試了IOException異常從一個方法拋出所謂readStream()和方法不拋出IOException異常,但Junit的失敗,並AssertionException測試。雖然拋出了相同的異常,但對於預期異常的JUnit測試失敗
private static StringBuilder readStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
finally {
try{
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder;
}
這裏是我的單元測試:
@SpringBootTest(classes = RequestResponseUtility.class)
public class RequestResponseUtilityTest extends AbstractTest {
@Mock
private InputStream inputStream;
@Test(expected = IOException.class)
public void convertStreamToStringNullTest() throws IOException {
RequestResponseUtility.convertStreamToString(inputStream);
}
}
我試過,你看,有在原來的類除外實際拋出異常,而不是僅僅捕捉並打印堆棧跟蹤:
e.printStackTrace();
throw e;
我使用註釋@Test(預期= IOException.class)並使用@rule方法也都嘗試。兩個測試都失敗了。我試過用@SpringBootTest(如上所示)和@RunWith(springjunit4classrunner.class)來標註我的測試。我真的很茫然。我得到這個錯誤
java.lang.AssertionError: Expected exception: java.io.IOException
但我的堆棧跟蹤
java.io.IOException: Underlying input stream returned zero bytes
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:288)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at main.java.utilities.RequestResponseUtility.readStream(RequestResponseUtility.java:25)
at main.java.utilities.RequestResponseUtility.convertStreamToString(RequestResponseUtility.java:45)
這是打破我的心臟。這不是一個大問題,不會影響我的代碼在生產中的性能,但我想了解爲什麼它實際上正在發生。
自己解決錯誤的好工作! –