Assert vs Softassert: What is Difference?
assert
vs soft assert
Both assert
and soft assert are used in testing to validate conditions, but they behave differently when a test case fails.
1. assert
(Hard Assertion)
- Stops execution immediately if the assertion fails.
- Used in JUnit (Java), pytest (Python), and Selenium for strict validations.
- If an assertion fails, the test case does not proceed beyond that point.
Example (Python – pytest):
def test_example():
assert 2 + 2 == 4 # Passes
assert 2 + 2 == 5 # Fails and stops execution here
print("This will not execute")
2. Soft Assert
- Does not stop execution immediately when an assertion fails.
- All assertions are recorded, and the test fails at the end if any assertion failed.
- Common in TestNG (Java) and Selenium WebDriver.
Example (Java – TestNG SoftAssert):
import org.testng.asserts.SoftAssert;
import org.testng.annotations.Test;
public class SoftAssertExample {
@Test
public void testSoftAssert() {
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(2 + 2, 4); // Passes
softAssert.assertEquals(2 + 2, 5); // Fails but test continues
System.out.println("Test continues even after failure");
softAssert.assertAll(); // Reports all failures at the end
}
}
Key Differences
Feature | assert (Hard Assert) | Soft Assert |
---|---|---|
Execution Stop | Yes, stops immediately | No, continues execution |
Use Case | Strict validations, critical failures | Non-critical assertions, multiple validations in one test |
Frameworks | pytest , unittest , JUnit, Selenium | TestNG (Java), Selenium WebDriver |
Reporting | Fails at the exact point of failure | Collects all failures and reports at the end |
Use hard assertions for critical checks and soft assertions when multiple checks need to be validated in a single test case.