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

如何在TestNG中移除失败信息里的java.lang.AssertionError及堆栈跟踪

Trim TestNG Assertion Failure to Show Only Custom Message

Got it, let's fix this problem where TestNG spits out the full AssertionError stack trace when you use Assert.fail("some message")—we just want to keep the custom message you wrote, no extra framework noise.

The Solution: Use a TestNG Listener to Clean Up Failure Details

Since you already started working with a listener, we can extend that approach by implementing ITestListener to intercept test failures and modify the error output exactly how you want.

Step 1: Create the Custom Listener

This listener will catch test failures, check if it's an AssertionError, then replace the full error with just your custom message (and strip out the stack trace entirely if needed):

import org.testng.ITestListener;
import org.testng.ITestResult;

public class CleanAssertionListener implements ITestListener {

    @Override
    public void onTestFailure(ITestResult result) {
        Throwable originalError = result.getThrowable();
        // Only modify AssertionErrors (leave other exceptions like runtime errors untouched)
        if (originalError instanceof AssertionError) {
            String customMessage = originalError.getMessage();
            // Create a new AssertionError with just your custom message
            AssertionError trimmedError = new AssertionError(customMessage);
            // Optional: Clear the stack trace completely to remove framework noise
            trimmedError.setStackTrace(new StackTraceElement[0]);
            // Update the test result to use our cleaned-up error
            result.setThrowable(trimmedError);
        }
    }

    // Implement other required listener methods with empty bodies (they're optional for our use case)
    @Override public void onTestStart(ITestResult result) {}
    @Override public void onTestSuccess(ITestResult result) {}
    @Override public void onTestSkipped(ITestResult result) {}
    @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {}
    @Override public void onStart(org.testng.ITestContext context) {}
    @Override public void onFinish(org.testng.ITestContext context) {}
}

Step 2: Register the Listener

You have two straightforward ways to hook this listener into your TestNG setup:

Option 1: Annotate Your Test Class

Add the @Listeners annotation directly to your test class (or a base test class if you have multiple tests):

import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import static org.testng.Assert.fail;

@Listeners(CleanAssertionListener.class)
public class BasicTest {
    @Test
    public void test() {
        fail("some message");
    }
}
Option 2: Configure in testng.xml

If you prefer central configuration for your entire test suite, add the listener to your test suite XML file:

<suite name="Your Test Suite">
    <listeners>
        <listener class-name="com.your.package.CleanAssertionListener"/>
    </listeners>
    <test name="Your Test">
        <classes>
            <class name="com.your.package.BasicTest"/>
        </classes>
    </test>
</suite>

How It Works

When you run your test and Assert.fail("some message") triggers a failure:

  1. The listener intercepts the failure event immediately
  2. It extracts your custom message from the original AssertionError
  3. It creates a new AssertionError with only your message (and clears the stack trace if you enabled that optional step)
  4. It updates the test result to use this cleaned-up error, so TestNG displays only your custom message in reports and logs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:36:14