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.
@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().
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:
@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:
| Feature | Hard Assert | Soft Assert |
|---|---|---|
| Class | Assert | SoftAssert |
| On failure | Stops test immediately | Continues test |
| Failures reported | First failure only | All failures |
| Report failures | Assert.assertEquals() | softAssert.assertAll() |
| Use case | Critical blockers | Multiple 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.
