1
votes

Below is a sample assertion method in TestNG framework.

private static void failAssertNoEqual(String defaultMessage, String message) {
    if (message != null) {
      fail(message);
    } else {
      fail(defaultMessage);
    }
  }

And here is the fail method.

/**
   * Fails a test with the given message.
   * @param message the assertion error message
   */
  public static void fail(String message) {
    throw new AssertionError(message);
  }

So when assertion fails, the test fails with an Assertion error.

In my case, I have to assert the content of a report. I would like my test to validate each columns and list the assertion failures than thrown out of the method on the very first failure. That way, I don't have to fix one field and rerun the test to verify the next field.

I tried to put each assertion in a Try Catch block, but that is making the code very lengthy.

   try {
            Assert.assertEquals("active", "inactive");
        }
        catch (AssertionError e) {
            //Store this somewhere
        }

Otherwise I will have to write custom functions perform each assertions, store them in a collection and finally pass or fail the test based on the values. But then I am not really making use of TestNG.

Is there a built-in method in TestNG to perform a soft assertion. If not, what is the ideal way to achieve this.

1

1 Answers

2
votes

You can use SoftAssert

public class ExampleTest {

 private SoftAssert softAssert = new SoftAssert();

 @Test
 public void test() {
     softAssert.assertTrue(false);
     softAssert.assertTrue(false);
     // your assertions
     softAssert.assertAll();
 }

    @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = ".* Message .*")
    public void exceptionTest() throws Exception {
        throw new IOException("IO Test");
    }

    @Test(expectedExceptions = { IOException.class, NullPointerException.class }, expectedExceptionsMessageRegExp = ".* Message .*")
    public void exceptionsTest() throws Exception {
        throw new IOException("IO Test");
    }