• March 20, 2025

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

Featureassert (Hard Assert)Soft Assert
Execution StopYes, stops immediatelyNo, continues execution
Use CaseStrict validations, critical failuresNon-critical assertions, multiple validations in one test
Frameworkspytest, unittest, JUnit, SeleniumTestNG (Java), Selenium WebDriver
ReportingFails at the exact point of failureCollects 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.

Leave a Reply

Your email address will not be published. Required fields are marked *