In the previous sections, we saw how to add Selenium TestNG to our automation project and how to use TestNG annotations to organize and control test execution.
Another important use case of the TestNG framework is Assertions.
What is an Assertion?
In test automation, assertions are validations used to compare the expected outcome with the actual outcome or verify that a certain condition is true. They help determine whether a test has passed or failed.
Assertion Syntax:
Use case Example:
Let’s say we’re writing an automation script for a login page:
1. The script enters the username and password
2. It clicks the login button
Now, we need to verify that the user has landed on the homepage correctly.
In manual testing, we can visually confirm that the homepage is displayed.
In automation, we use assertions to verify that a specific element, like a homepage heading, appears correctly after login.
Example Code using TestNG Assertions
If the assertion passes, the test will be marked as passed. If the assertion fails, the test is marked as failed and stops execution at that point.
Assertion |
Description |
Assert.assertEquals(actual, expected) |
Verifies two values are equal |
Assert.assertTrue(condition) |
Verifies the condition is true |
Assert.assertFalse(condition) |
Verifies the condition is false |
Assert.assertNotEquals(actual, expected) |
Verifies two values are not equal |
Assert.assertNull(object) |
Verifies the object is null |
Assert.assertNotNull(object) |
Verifies the object is not null |
Types of Assertion
TestNG supports two types of assertions:
Hard Assertions:
1. Immediately stop test execution when an assertion fails.
2. Code written after the failed assertion will not be executed.
Soft Assertions:
1. Continue test execution even if an assertion fails.
2. All assertion results are collected and reported at the end.
3. Must call assertAll() at the end to log the results.
To know more about TestNG Assertions, follow this link: TestNG Assertions
For our complete TestNG Tutorial, follow this link: TestNG Tutorial