Selenium is one of the most popular tools for automating web applications. In test automation, Assertions play a crucial role in verifying that the application behaves as expected. Assertions help validate test outcomes, ensuring that expected and actual results match.
In this blog, we’ll explore what assertions are, their types in Selenium, and how to use them effectively.
1. What are Assertions in Selenium?
Assertions in Selenium are used to verify expected conditions in a test case. If an assertion fails, the test case is marked as failed, indicating an issue in the application. Assertions ensure that:
✔ The web application behaves as expected.
✔ Test cases stop execution upon failure (for hard assertions).
✔ Errors are caught early in the testing cycle.
Selenium provides assertions through JUnit and TestNG frameworks.
2. Types of Assertions in Selenium
a) Hard Assertions
Hard Assertions immediately stop test execution when an assertion fails. They ensure that a test case does not proceed if a critical condition is not met.
🔹 Example (TestNG – Hard Assert):
import org.testng.Assert;
import org.testng.annotations.Test;
public class HardAssertionExample {
@Test
public void testTitle() {
String expectedTitle = "Google";
String actualTitle = "Google"; // Assume fetched from WebDriver
Assert.assertEquals(actualTitle, expectedTitle, "Title mismatch!");
System.out.println("This will execute only if assertion passes.");
}
}
If actualTitle
does not match expectedTitle
, the test will fail, and execution stops.
b) Soft Assertions
Soft Assertions allow the test to continue executing even if an assertion fails. They collect all assertion results and fail the test at the end if necessary.
🔹 Example (TestNG – Soft Assert):
import org.testng.asserts.SoftAssert;
import org.testng.annotations.Test;
public class SoftAssertionExample {
@Test
public void testSoftAssert() {
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals("Google", "Yahoo", "Title mismatch!");
softAssert.assertTrue(10 > 20, "Condition failed!");
System.out.println("Test continues even after failures.");
softAssert.assertAll(); // Marks test as failed if any assertion fails
}
}
Soft assertions collect failures and fail the test only after assertAll()
is called.
3. Commonly Used Assertions in Selenium
Assertion | Description |
---|---|
Assert.assertEquals(actual, expected) |
Verifies values are equal. |
Assert.assertTrue(condition) |
Checks if condition is true. |
Assert.assertFalse(condition) |
Ensures a condition is false. |
Assert.assertNotNull(object) |
Ensures object is not null. |
4. Conclusion
Assertions in Selenium are essential for validating web applications. Hard assertions stop execution immediately, while soft assertions allow multiple checks before marking a test as failed. Using assertions effectively improves test reliability and helps catch defects early.
🚀 Start using assertions in Selenium today to enhance your automation tests!