Soft assertions and hard assertions are two different approaches to handling assertions in test automation frameworks like TestNG or JUnit. Both serve the purpose of validating expected outcomes during test execution, but they differ in how they handle failures.
Hard Assertions:
- Hard assertions are the traditional form of assertions where the test execution stops as soon as an assertion fails.
- When a hard assertion fails, the test immediately terminates, and no further test steps in the current test case are executed.
- Hard assertions are suitable when subsequent test steps are dependent on the success of previous steps, and there’s no point in continuing the test if a critical condition fails.
Example:
public class HardAssertExample {
@Test
public void testHardAssert() {
int actual = 10;
int expected = 15;
Assert.assertEquals(actual, expected, “Values are not equal”);
// If assertion fails, the test execution stops here.
System.out.println(“This line will not be executed if assertion fails.”);
}
}
Soft Assertions:
- Soft assertions allow the test execution to continue even after an assertion failure. All assertions are evaluated, and a comprehensive report of all failures is generated at the end of the test.
- Soft assertions are useful when you want to collect multiple validation failures within a single test case without aborting the test prematurely. This can be helpful for scenarios where you need to verify multiple aspects of the system’s behavior.
Example:
public class SoftAssertExample {
@Test
public void testSoftAssert() {
SoftAssert softAssert = new SoftAssert();
int actual = 5;
int expected = 10;
softAssert.assertEquals(actual, expected, “Values are not equal”);
// Test execution continues even after assertion failure.
System.out.println(“This line will be executed even if assertion fails.”);
softAssert.assertAll(); // This line is essential to collect all assertion failures.
}
}
Hard assertions are more rigid and stop test execution upon failure, while soft assertions allow the test to continue and collect multiple failures before reporting them at the end of the test. The choice between hard and soft assertions depends on the specific requirements of your test cases and the level of detail you need in your test reports.