</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

What is the difference between verify and assert in Selenium TestNG?

Answer

Verify vs Assert in Selenium TestNG

Assert (Hard Assertion): Checks a condition. If it fails, the test method stops immediately — no further code executes.

Java
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().

Java
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:

Java
@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:

FeatureAssert (Hard)Verify (SoftAssert)
On failureStops test immediatelyContinues test
ReportsFirst failure onlyALL failures
ClassAssertSoftAssert
End call neededNoYes — assertAll()
TestNG behaviorTest = FAILED (immediately)Test = FAILED at assertAll()

When to use which:

ScenarioUse
Critical step (login must pass to continue)Assert
UI validation (check multiple elements)Verify (SoftAssert)
Sequential dependenciesAssert
Independent checks on same pageVerify (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.

Follow AutomateQA

Related Topics