在 TestNg 软断言中显示 assertEquals 错误消息以及给定自定义消息的任何方式

Any way to show assertEquals error message along with the given custom message in TestNg soft assertion

这里是 link to a related question

有什么方法可以显示默认的 assertEquals 错误消息以及软断言中给出的自定义消息?

我的要求是具有如下自定义消息和断言错误消息。 “打破预期 [1] 但发现 [0]”

import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
    
public class SoftAsert
{
    @Test
    public void test()
    {
        SoftAssert asert=new SoftAssert();
        asert.assertEquals(false, true,"failed");
        asert.assertEquals(0, 1,"brokedown");
        asert.assertAll();
    }
}

您可以创建自己的 SoftAssert,这应该能发挥神奇作用:

public class MySoftAssert extends Assertion
{
    // LinkedHashMap to preserve the order
    private Map<AssertionError, IAssert> m_errors = Maps.newLinkedHashMap();

    @Override
    public void executeAssert(IAssert a) {
        try {
            a.doAssert();
        } catch(AssertionError ex) {
            onAssertFailure(a, ex);
            m_errors.put(ex, a);
        }
    }

    public void assertAll() {
        if (! m_errors.isEmpty()) {
            StringBuilder sb = new StringBuilder("The following asserts failed:\n");
            boolean first = true;
            for (Map.Entry<AssertionError, IAssert> ae : m_errors.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    sb.append(", ");
                }
                sb.append(ae.getKey().getMessage());
            }
            throw new AssertionError(sb.toString());
        }
    }
}