</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

What is the difference between soft assertion and hard assertion in TestNG?

Hard assertions stop test execution immediately on failure. Soft assertions allow the test to continue and collect all failures, reported at the end via assertAll().

Answer

Soft Assertion vs Hard Assertion in TestNG

Hard Assertions (default Assert class): The usual assertions from TestNG. If any assertion fails, the test method stops immediately — no further steps are executed.

Java
@Test
public void hardAssertionTest() {
    Assert.assertEquals(driver.getTitle(), "Home Page");  // If this fails...
    System.out.println("This line is NOT reached if assertion above fails");
    Assert.assertTrue(element.isDisplayed());  // This is also skipped
}

Soft Assertions (SoftAssert class): Allows multiple assertions in one test — even if one fails, the test continues executing. All failures are collected and reported together at the end via assertAll().

Java
import org.testng.asserts.SoftAssert;

@Test
public void softAssertionTest() {
    SoftAssert softAssert = new SoftAssert();

    // Assertion failing — but test continues
    softAssert.fail();
    System.out.println("Failing");  // This IS printed despite the failure above

    // Assertion passing
    softAssert.assertEquals(1, 1);
    System.out.println("Passing");  // This is also printed

    // Collates all assertion results — test is marked FAIL here
    softAssert.assertAll();
}

Another soft assert example:

Java
@Test
public void verifyHomePage() {
    SoftAssert sa = new SoftAssert();

    sa.assertEquals(driver.getTitle(), "Home Page", "Title mismatch");
    sa.assertTrue(logo.isDisplayed(), "Logo not visible");
    sa.assertFalse(errorBanner.isDisplayed(), "Error banner should be hidden");
    sa.assertNotNull(driver.findElement(By.id("search")), "Search box missing");

    // Reports ALL failures at once
    sa.assertAll();
}

Comparison table:

FeatureHard AssertSoft Assert
ClassAssertSoftAssert
On failureStops test immediatelyContinues test
Failures reportedFirst failure onlyAll failures
Report failuresAssert.assertEquals()softAssert.assertAll()
Use caseCritical blockersMultiple validations

When to use which:

  • Hard Assert → When subsequent steps depend on the assertion (e.g., login must succeed before checking dashboard)
  • Soft Assert → When you want to check multiple UI elements in one test and get a complete picture of what failed

Critical rule: Always call softAssert.assertAll() at the end — without it, soft assertion failures are silently ignored.

Follow AutomateQA

Related Topics