Selenium软断言assertAll()如何仅打印失败断言不输出堆栈信息
解决SoftAssert调用assertAll输出冗余堆栈的方案
TestNG 原生 SoftAssert 的 assertAll() 方法执行时,会将所有失败断言的完整堆栈信息封装到抛出的 AssertionError 中,最终导致控制台输出大量冗余堆栈内容。
方案1:自定义SoftAssert实现(零配置,灵活度高)
继承原生SoftAssert重写逻辑,仅收集失败提示信息,最终抛出无堆栈的自定义异常,输出仅包含失败内容和统计结果:
import org.testng.asserts.SoftAssert; import org.testng.asserts.AssertionError; import java.util.ArrayList; import java.util.List; public class CustomSoftAssert extends SoftAssert { // 存储所有失败断言的自定义提示 private final List<String> failedMsgs = new ArrayList<>(); @Override public void onAssertFailure(org.testng.asserts.IAssert<?> assertCommand, Throwable t) { failedMsgs.add(assertCommand.getMessage()); super.onAssertFailure(assertCommand, t); } @Override public void assertAll() { if (failedMsgs.isEmpty()) { return; } // 构造自定义输出内容 StringBuilder output = new StringBuilder(); output.append("软断言运行完成,共失败 ").append(failedMsgs.size()).append(" 项:\n"); for (int i = 0; i < failedMsgs.size(); i++) { output.append(i + 1).append(". ").append(failedMsgs.get(i)).append("\n"); } // 抛出无堆栈的异常,避免输出冗余栈信息 AssertionError error = new AssertionError(output.toString()); error.setStackTrace(new StackTraceElement[0]); throw error; } }
使用时将原有代码中的SoftAssert sa = new SoftAssert();替换为CustomSoftAssert sa = new CustomSoftAssert();即可生效。
方案2:TestNG监听器全局过滤(无需修改业务代码)
如果不想调整现有业务代码中SoftAssert的引用,可以通过实现TestNG的监听器全局过滤SoftAssert异常的堆栈信息:
import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.asserts.AssertionError; public class SoftAssertStackFilter implements IInvokedMethodListener { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { Throwable throwable = testResult.getThrowable(); // 匹配SoftAssert抛出的汇总异常 if (throwable instanceof AssertionError && throwable.getMessage() != null && throwable.getMessage().startsWith("The following asserts failed:")) { // 清空异常堆栈 throwable.setStackTrace(new StackTraceElement[0]); testResult.setThrowable(throwable); } } }
配置方法:将上述监听器添加到testng.xml的监听器列表中,即可全局生效,所有SoftAssert的assertAll输出都不会再携带堆栈信息。
- 两种方案均不会丢失断言失败的核心提示,可根据业务场景自行选择。
内容的提问来源于stack exchange,提问作者deokyong song
相关产品推荐
相关产品推荐

