Verify vs Assert in Selenium TestNG
Assert (Hard Assertion): Checks a condition. If it fails, the test method stops immediately — no further code executes.
Assert.assertEquals(driver.getTitle(), "Home Page");
// If this fails, all code below is NOT executed
System.out.println("This line is skipped if assertion failed");
Verify (Soft Assertion — SoftAssert):
Checks a condition. If it fails, the test method continues executing. All failures are collected and reported together at the end via assertAll().
SoftAssert sa = new SoftAssert();
sa.assertEquals(driver.getTitle(), "Home Page");
// Even if this fails, execution continues
System.out.println("This line IS executed even if assertion above failed");
sa.assertTrue(element.isDisplayed());
sa.assertAll(); // Reports all failures here
Side-by-side comparison:
@Test
public void hardAssertTest() {
Assert.assertEquals(1, 2); // FAILS → test stops
System.out.println("Never reached");
}
@Test
public void softAssertTest() {
SoftAssert sa = new SoftAssert();
sa.assertEquals(1, 2); // FAILS → but continues
System.out.println("This IS printed");
sa.assertEquals(3, 3); // PASSES
sa.assertAll(); // Reports: 1 failure
}
Summary table:
| Feature | Assert (Hard) | Verify (SoftAssert) |
|---|---|---|
| On failure | Stops test immediately | Continues test |
| Reports | First failure only | ALL failures |
| Class | Assert | SoftAssert |
| End call needed | No | Yes — assertAll() |
| TestNG behavior | Test = FAILED (immediately) | Test = FAILED at assertAll() |
When to use which:
| Scenario | Use |
|---|---|
| Critical step (login must pass to continue) | Assert |
| UI validation (check multiple elements) | Verify (SoftAssert) |
| Sequential dependencies | Assert |
| Independent checks on same page | Verify (SoftAssert) |
Key rule: Always call sa.assertAll() at the end of a soft assert test — without it, failures are silently ignored and the test passes incorrectly.
