You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TestNG测试catch块中的FileNotFoundException及输出信息?

测试FileNotFoundException捕获逻辑的TestNG用例

被测试类示例

先把业务逻辑封装到类中,方便测试:

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FileHandler {
    public void readFile(String filePath) {
        try {
            // 故意触发FileNotFoundException
            new FileInputStream(filePath);
        } catch (FileNotFoundException ex) {
            System.out.println("File does't exit, please put the file inside resources folder.");
            ex.printStackTrace();
        }
    }
}

TestNG测试类实现

通过重定向输出流捕获控制台内容,验证预期输出:

import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class FileHandlerTest {
    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
    private final PrintStream originalOut = System.out;
    private final PrintStream originalErr = System.err;
    private FileHandler fileHandler;

    @BeforeMethod
    public void setUpStreams() {
        // 重定向输出流,用于捕获控制台内容
        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));
        fileHandler = new FileHandler();
    }

    @Test
    public void testFileNotFoundExceptionHandling() {
        // 传入不存在的文件路径,触发异常
        fileHandler.readFile("non-existent-file.txt");

        // 验证指定提示信息是否输出
        String expectedTip = "File does't exit, please put the file inside resources folder.";
        Assert.assertTrue(outContent.toString().contains(expectedTip),
                "未输出指定的异常提示文本");

        // 验证异常栈跟踪是否打印(检查是否包含异常类名)
        Assert.assertTrue(errContent.toString().contains("FileNotFoundException"),
                "未打印FileNotFoundException的栈跟踪信息");
    }

    @AfterMethod
    public void restoreStreams() {
        // 恢复原始输出流,避免影响其他测试
        System.setOut(originalOut);
        System.setErr(originalErr);
    }
}

关键说明

  • 输出流重定向:在@BeforeMethod中将System.out和System.err重定向到字节数组输出流,既能捕获控制台内容,又不会污染测试时的控制台输出。
  • 断言逻辑:
    • 检查System.out的输出是否包含指定提示字符串
    • 检查System.err的输出是否包含异常类名(printStackTrace()默认输出到System.err)
  • 资源恢复:在@AfterMethod中恢复原始输出流,保证其他测试用例不受影响。

内容的提问来源于stack exchange,提问作者Jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:30:48