如何在控制台上打印异常?我正在使用 TestNG 和 Maven

问题描述

我想在控制台上查看异常。我将 TestNG 与 Maven 一起用作构建工具。我已经在 Maven surefire 插件中定义了我的 testng.xml。

解决方法

https://www.javadoc.io/doc/org.testng/testng/latest/org/testng/reporters/VerboseReporter.html

你应该使用上面的reporter,但是构造函数需要一个字符串,所以你不能用testng.xml初始化它(如果有人知道如何将字符串参数传递给testng.xml中的侦听器,请在此处添加)

所以解决方法是通过脚本添加监听器并通过java入口文件启动testng。

public static void main(String[] args) {


        TestNG testng = new TestNG();

        // Create a list of String
        List<String> suitefiles = new ArrayList<String>();

        // Add xml file which you have to execute
        suitefiles.add(prop.getProperty("path_to_your_existing_testngxml\testng.xml"));

        // now set xml file for execution
        testng.setTestSuites(suitefiles);
        
        testng.addListener(new VerboseReporter("[TestNG] "));

        // finally execute the runner using run method
        testng.run();

}

输出:

enter image description here

注意

由于这个报告器构造函数需要一个字符串,你不应该在你的 testng.xml 中提供它,你会得到初始化错误

,

如果您使用任何类型的日志框架,您可能应该坚持使用它。 否则,您始终可以使用 https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#printStackTrace()(和兄弟姐妹)打印异常,例如

...
} catch (Exception e) {
    e.printStackTrace(System.out);
    e.printStackTRace(System.err);
}
...