Selenium

How To Use TestNG Assertions in Selenium | Soft & Hard Assertions

How To Use TestNG Assertions in Selenium

By Bhau Automation • Learn Hard & Soft Assertions with Examples

💡 Hard vs Soft Assertions

  • Hard Assertion: Stops execution on first failure. Assert.assertEquals(actual, expected);
  • Soft Assertion: Continues execution after failures, reports all at the end.
    SoftAssert softAssert = new SoftAssert();
    softAssert.assertEquals(actual, expected);
    softAssert.assertAll();
          

🔹 Commonly Used TestNG Assertions

  • assertEquals(String actual, String expected) – Asserts two strings are equal.
  • assertEquals(String actual, String expected, String message) – Adds a custom failure message.
  • assertEquals(boolean actual, boolean expected, String message) – Compares two boolean values.
  • assertTrue(condition) – Checks that a condition is true.
  • assertTrue(condition, message) – Checks condition with a custom message on failure.
  • assertFalse(condition) – Checks that a condition is false.
  • assertFalse(condition, message) – Checks condition with a custom failure message.

💻 Practical Example

import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;

public class TestNGAssertionsDemo {

    @Test
    public void hardAssertionsTest() {
        String expected = "Bhau";
        String actual = "Bhau";
        Assert.assertEquals(actual, expected, "Strings do not match!");
    }

    @Test
    public void softAssertionsTest() {
        SoftAssert softAssert = new SoftAssert();
        softAssert.assertEquals("Hello", "Hi", "Strings do not match!");
        softAssert.assertTrue(5 > 10, "Condition failed!");
        softAssert.assertAll();
    }
}
  

🎯 Key Takeaways

  • Hard assertions stop execution immediately on failure.
  • Soft assertions allow multiple validations in a single test method.
  • Always use softAssert.assertAll() to report soft assertion results.
  • Assertions are critical to validate expected vs actual results in Selenium automation.
Pro Tip: Combine hard and soft assertions strategically for efficient test validation and reporting.

🚀 Created with ❤️ by Bhau Automation

Back to All Articles