[英]How to test catch block in testNG JAVA
你能幫我創建一個測試用例來測試這個catch
塊嗎?
try { //something here
}catch (FileNotFoundException ex) {
System.out.println("File does't exit, please put the file inside resources folder.");
ex.printStackTrace();
}
我想測試這條消息“文件不退出,請將文件放在資源文件夾中。” 和FileNotFoundException
異常使用testNG
。
試試這個代碼,你會得到 FileNotFoundException,文件 'test.txt' 不應該在路徑中可用:
try {
File file = new File("C:\\Users\\test\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
System.out.println(sc.next());
sc.close();
} catch (FileNotFoundException e) {
System.out.println("In catch block");
e.printStackTrace();
}
理想情況下,您不使用系統 output。 您寧願注入一個記錄器並對此進行測試。
但是,還是可以做到的
// Store the original standard out before changing it.
private final PrintStream originalStdOut = System.out;
private ByteArrayOutputStream consoleContent = new ByteArrayOutputStream();
@BeforeMethod
public void beforeTest() {
// Redirect all System.out to consoleContent.
System.setOut(new PrintStream(this.consoleContent));
}
您可能需要對System.err
for ex.printStackTrace()
output 執行類似的操作...
然后在標准測試中運行您的 function,並針對consoleContent
內容進行斷言。
每次測試后,您都需要重置 stream,如果您仍然想打印數據,那么也這樣做
@AfterMethod
public void afterTest() {
// Put back the standard out.
System.setOut(this.originalStdOut);
// Print what has been captured.
System.out.println(this.consoleContent.toString());
System.out.println(String.format(" ====>Captured Console length=%d",
this.consoleContent.toString().length()));
// Clear the consoleContent.
this.consoleContent = new ByteArrayOutputStream();
}
或者,更理想的是,您定義自己的 RuntimeException / Exception 子類,然后使用 assertThrows 方法,您可以在其中正確驗證異常 object 內容,包括消息正文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.