有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使TestNG报告显示软断言失败的行

我正在使用Selenium、Java和TestNG编写测试。有时我在单元测试中使用许多软断言,当它们失败时,TestNG reporter不会显示它们发生的代码行。有没有办法让它表现出来?实际上,当我点击Failure Exception上的报告时,它会把我带到s_assert.assertAll();,但我需要被带到特定的行,例如:s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect");


共 (1) 个答案

  1. # 1 楼答案

    下面的自定义软断言实现(我将其命名为Verifier)应该满足您的要求

    import org.testng.annotations.Test;
    import org.testng.asserts.Assertion;
    import org.testng.asserts.IAssert;
    import org.testng.collections.Maps;
    
    import java.util.Arrays;
    import java.util.Map;
    
    public class SoftAssertExample {
        private Verifier verifier = new Verifier();
    
        @Test
        public void testMethod() {
            verifier.assertEquals(false, true);
            verifier.assertTrue(true);
            verifier.assertAll();
        }
    
        /**
         * A simple soft assertion mechanism that also captures the stacktrace to help pin point the source
         * of failure.
         */
        public static class Verifier extends Assertion {
            private final Map<AssertionError, IAssert<?>> m_errors = Maps.newLinkedHashMap();
    
            @Override
            protected void doAssert(IAssert<?> a) {
                onBeforeAssert(a);
                try {
                    a.doAssert();
                    onAssertSuccess(a);
                } catch (AssertionError ex) {
                    onAssertFailure(a, ex);
                    m_errors.put(ex, a);
                } finally {
                    onAfterAssert(a);
                }
            }
    
            public void assertAll() {
                if (! m_errors.isEmpty()) {
                    StringBuilder sb = new StringBuilder("The following asserts failed:");
                    boolean first = true;
                    for (Map.Entry<AssertionError, IAssert<?>> ae : m_errors.entrySet()) {
                        if (first) {
                            first = false;
                        } else {
                            sb.append(",");
                        }
                        sb.append("\n\t");
                        sb.append(ae.getKey().getMessage());
                        sb.append("\nStack Trace :");
                        sb.append(Arrays.toString(ae.getKey().getStackTrace()).replaceAll(",", "\n"));
                    }
                    throw new AssertionError(sb.toString());
                }
            }
        }
    }