我正在使用 Selenium、Java 和 TestNG 编写测试。有时我在单元测试中使用了许多软断言,当它们失败时,TestNG 报告器不会显示它们发生的代码行。有没有办法让它显示出来?实际上,当我点击报告时,Failure Exception
它会带我去,s_assert.assertAll();
但我需要被带到特定的行,例如:s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect");
问问题
4409 次
3 回答
3
以下自定义软断言的实现(我将其命名为验证器)应该可以满足您的要求。
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());
}
}
}
}
于 2016-05-16T03:50:37.680 回答
2
这是一个延迟的答案,但我想我会分享我的解决方案,因为我遇到了同样的问题。
下面打印出软断言的线路故障的位置。它显示了正在使用的类的方法内部的线路故障,如下所示:
1)
Error: Custom error message goes here
[Class -> path.to.class.shows.here.ExampleClassName]
[Method -> exampleMethod]
[Line -> 342]
此解决方案的示例代码:
public void assertIsTrueSoftly(String errorMsg, boolean condition) {
String trace = null;
if (!condition) {
Throwable throwable = new Throwable();
trace =
String.format(
"[Class -> %s]%n[Method -> %s]%n[Line -> %d]",
throwable.getStackTrace()[1].getClassName(),
throwable.getStackTrace()[1].getMethodName(),
throwable.getStackTrace()[1].getLineNumber());
}
soft.assertThat(condition).withFailMessage(format("%nError: %s%n%s", errorMsg, trace)).isTrue();
}
于 2019-07-11T17:12:32.163 回答
0
示例代码:
s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect1");
s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect2");
s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect3");
s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect4");
s_assert.assertall();
执行失败后它指向(s_assert.assertall();)
行,同时它显示软断言失败的消息....
Alert Is InCorrect2
Alert Is InCorrect3
请检查输出。
于 2016-05-16T05:38:51.767 回答