Reputation: 63
Here's a link to a related question.
Is there any way to display the default assertEquals error message along with the custom message given in soft assertion?
My requirement is to have custom message and assert error message as below. "broke down expected [1] but found [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();
}
}
Upvotes: 3
Views: 2636
Reputation: 3105
You can create your own SoftAssert, this should do the magic:
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());
}
}
}
Upvotes: 2