我正在使用Selenium,Java和TestNG编写测试。有时,我在单元测试中会使用许多软断言,而当它们失败时,TestNG报告程序不会显示发生的代码行。有什么办法可以表明这一点吗?实际上,当我单击Failure Exception
上的报告时,它会将我带到s_assert.assertAll();
,但是我需要转到特定的行,例如:s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect");
最佳答案
下面的自定义软断言(我将其命名为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());
}
}
}
}