I am using Selenium, Java and TestNG to write tests. Sometimes I use many soft assertions in my unit tests and when they fail the TestNG reporter does not show the line of the code that they happened. Is there any way to make it show that? actually when I click on the report at Failure Exception
it takes me to s_assert.assertAll();
but I need to be taken to the specific lines, such as: s_assert.assertEquals(Alert_text, "Hi.. is alert message!", "Alert Is InCorrect");
The below implementation of a custom Soft Assertion (I have named it Verifier) should do what you are asking for.
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());
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With