Hard and Soft Assertions

Hard Assert

Assert.assertEquals(actual, expected, message) stops the test at the first failure. Note the order in TestNG: actual first, expected second (JUnit is the opposite).

Assert.assertEquals(driver.findElement(By.id("cart-count")).getText(), "2", "cart count");
Assert.assertTrue(driver.findElement(By.id("checkout")).isEnabled(), "checkout enabled");
Assert.assertFalse(driver.findElements(By.cssSelector(".error-message")).size() > 0, "no error shown");

Example

When the first assertion fails:

mvn test -Dtest=CartTest

Example output

[ERROR] cartShowsTwoItems(com.shopease.tests.CartTest)  Time elapsed: 3.881 s  <<< FAILURE!
java.lang.AssertionError: cart count expected [2] but found [1]

Soft Assert

import org.testng.asserts.SoftAssert;

@Test
public void productPageDetails() {
    SoftAssert soft = new SoftAssert();
    soft.assertEquals(driver.findElement(By.cssSelector("h1")).getText(), "Nike Revolution 7", "name");
    soft.assertEquals(driver.findElement(By.cssSelector(".price")).getText(), "₹1,299", "price");
    soft.assertTrue(driver.findElement(By.id("add-to-cart")).isEnabled(), "add button");
    soft.assertAll();   // REQUIRED: reports all failures together
}

Note: Without assertAll() a soft-assert test always passes. Use soft asserts to check many fields on one page; use hard asserts when the next steps make no sense after a failure (e.g. login failed).

How Soft Assert Works

Example

A tiny soft-assert class in plain Java: it collects failures and throws once at the end:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        MySoftAssert soft = new MySoftAssert();
        soft.assertEquals("Nike Revolution 7", "Nike Revolution 7", "name");
        soft.assertEquals("₹1,399", "₹1,299", "price");
        soft.assertEquals("Out of stock", "In stock", "stock");
        try {
            soft.assertAll();
        } catch (AssertionError e) {
            System.out.println(e.getMessage());
        }
    }
}

class MySoftAssert {
    private final List<String> errors = new ArrayList<>();

    void assertEquals(Object actual, Object expected, String message) {
        if (!Objects.equals(actual, expected)) {
            errors.add(message + " expected [" + expected + "] but found [" + actual + "]");
        }
    }

    void assertAll() {
        if (!errors.isEmpty()) throw new AssertionError("The following asserts failed:\n\t" + String.join(",\n\t", errors));
    }
}

Output

The following asserts failed:
	price expected [₹1,299] but found [₹1,399],
	stock expected [In stock] but found [Out of stock]