Difference between hard and soft assertion in Testng

Assertions help to verify the expected data with application using Testng with Selenium. We have different kind of assertions are available for verification such as Hard assertions and Soft assertions. Hard assertions used to failed the test execution whenever the mismatch found with exception and soft assertions continue the test execution when assertions is failed. Below is the examples are provided for both Hard and soft assertions in selenium with Java and Testng.

Hard Assertion in selenium with Testng using Java: Example: Hard assertions can be performed using Assert class with method assertEquals as follows:

package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class VerifyTitle {

WebDriver driver = null;

@Test
public void hardAssertion() {

    try {
        driver = new ChromeDriver();
        driver.get("https://www.google.com");

        String expTitle = "Google Local";
        String actualTitle = "";

        actualTitle = driver.getTitle();

        Assert.assertEquals(expTitle, actualTitle);

    } catch (Exception ex) {
        System.out.print(ex.getMessage());
    }
}

}

As we see in the image below test execution is failed due to mismatch with title ‘Yahoo’ and ‘Google’

SoftAssertion in selenium with Testng using Java: Implemente SoftAssert class and provide the assertions in the example below and used assertAll() method for performing assertions.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;

public class HardAndSoftAssertion {

WebDriver driver = null;

@Test
public void verifySoftAssertion() {

    try {
        driver = new ChromeDriver();
        driver.get("https://www.google.com");

        String expTitle = "Yahoo";
        String actualTitle = "";

        actualTitle = driver.getTitle();

        SoftAssert softassert = new SoftAssert();
        softassert.assertEquals(expTitle, actualTitle);
      
        softassert.assertAll();

    } catch (Exception ex) {
        System.out.print(ex.getMessage());
    }
}

}

As we see in the screenshot below test execution test is passed even with mismatch wit title ‘Google’ with ‘Yahoo’

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x