soft & hard assertion with example

How to handle “Assertions” in Selenium TestNG Project?

Testng soft assertion and hard assertion! The primary purpose of Automation Testing is the assertion of our actual result with the expected result. For assertion, we use various testing frameworks like JUnit, TestNG, Hamcrest (in Java), PyTest (in Python) and N Unit(.Net Framework). In this tutorial, we will learn about Testing Hard Assertion and Soft Assertion and will explain why we need to use Soft Assertion and Hard Assertion, what is an assertion and how we will use hard & soft assertion in the Automation script.

Scenario 1: When Hard Assertion is required?

Suppose we have to Login at one portal and verify user profile section. But suppose you failed to log in then there will be no meaning to continue test further. So, here we need to use Hard Assertion (by default we say “Assertion”). No need to worry if you are not aware of Hard Assertion. Refer below and read with patience, We assure you will get it & at the end of the tutorial you will successfully understand about Soft Assertion and Hard Assertion.

Login Portal

Scenario 2: When Soft Assertion is required?

In the second scenario, you logged In successfully and navigated to user profile section but you observed that few fields texts value are not as you expected. At this point, you don’t require to fail & stop test execution but you will surely continue your test execution, complete the test, will collect all failures at once and at the end, you will print all the consolidated failures in the report. In this type of scenario’s, we use TestNG Soft Assertion

Pre-requisite:

  1. Selenium and TestNG Project should be set up (If not set up then refer our blog- Set up Selenium & TestNG in Maven Project)

What is Hard Assertion?

Hard Assertions: Hard Assertions are a type of assertions which immediately throws an exception on test failure and abort test. Automation script throws exception “java.lang.AssertionError:”

Hard Assertion Console Error
Hard Assertions

Refer below for step by step guide and code explanation:

  • Step 1: Create testClass and Write BeforeMethod method:

Create class “AssertExample” and write before the test method to open a browser and navigate to URL. (BeforeMethod is executed before each method execution. Refer our article for before method).

public class AssertExample {
 
// As WebDriver used in every method of this class so making it public
    public static WebDriver driver=null;
// Before Method executed before every Method. 
    @BeforeMethod
    public void setUp() {
        WebDriverManager.chromedriver().version("83.0.4103.61").setup();
        driver = new ChromeDriver();
        driver.get("http://newtours.demoaut.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }
 
}
  • Step 2: Write Test Method  for Hard Assertion:
@Test
public void LoginVerifyWithHardAssert() throws InterruptedException {
    driver.findElement(By.xpath("//input[@name='userName']")).sendKeys("mercury");
    driver.findElement(By.xpath("//input[@name='password']")).sendKeys("mercury");
    driver.findElement(By.xpath("//input[@name='login']")).click();
    Thread.sleep(5000);
    String pageTitle = driver.getTitle();
    System.out.println("Page Title: " + pageTitle);
 
// Failed below assertion to show Hard Assertions. At this step execution stopped and 
// your programme throws java.lang.AssertionError and no further execution //happens
    Assert.assertEquals(pageTitle, "Find a Flight: Mercury Tours:-Hard 1");
    driver.findElement(By.xpath("//input[@name='findFlights']")).click();
    String selectPageTitle = driver.getTitle();
    System.out.println("Page Title: " + selectPageTitle);
    Assert.assertEquals(selectPageTitle, "Select a Flight: Mercury Tours-Hard 2");
    driver.findElement(By.xpath("//input[@name='reserveFlights']")).click();
    driver.findElement(By.xpath("//input[@name='buyFlights']")).click();
    Thread.sleep(7000);
    driver.close();
    System.out.println("Test Completed!");
}

Console Output:

Console Error Hard assertion

What is Soft Assertion in Selenium?

Soft Assertions: As we already saw that Hard Assert terminates on the first failure. But sometimes we want to complete all the test in spite of a few failures and notify all failures at the end of execution.

Soft Assertions class in TestNG is widely used in the verification of test result. Refer below for step by step guide

  • Step 3: Write a method to verify flight booking

BookFlightVerifyWithSoftAssert() using Soft Assertions:

          Make object of SoftAssert class

SoftAssert soft = new SoftAssert();

          Use Soft Assert object soft for verification of actual result with the expected result.

soft.assertEquals(pageTitle, "Select a Flight: Mercury Tours1");

          At the end of all assertions, you need to use assert() for validating all the verification steps.

soft.assertAll();

         Write method BookFlightVerifyWithSoftAssert() code

public void BookFlightVerifyWithSoftAssert() throws InterruptedException {
    driver.findElement(By.xpath("//input[@name='userName']")).sendKeys("mercury");
    driver.findElement(By.xpath("//input[@name='password']")).sendKeys("mercury");
    driver.findElement(By.xpath("//input[@name='login']")).click();
    SoftAssert soft = new SoftAssert();
    Thread.sleep(5000);
    String pageTitle = driver.getTitle();
    System.out.println("Page Title: " + pageTitle);
    soft.assertEquals(pageTitle, "Select a Flight: Mercury Tours1");
    driver.findElement(By.xpath("//input[@name='findFlights']")).click();
    String selectPageTitle = driver.getTitle();
    System.out.println("Page Title: " + selectPageTitle);
    soft.assertEquals(selectPageTitle, "Select a Flight: Mercury Tours2");
    driver.findElement(By.xpath("//input[@name='reserveFlights']")).click();
    driver.findElement(By.xpath("//input[@name='buyFlights']")).click();
    Thread.sleep(7000);
    String confirmationPageTitle = driver.getTitle();
    System.out.println("Confirmation Page Title: "+confirmationPageTitle);
    soft.assertEquals(confirmationPageTitle, "");
    driver.close();
    System.out.println("Test Completed!");
    soft.assertAll();
}
  • Step 4: Write after Test method to close the browser and quit WebDriver instance
@AfterTest
public void closeSetUp(){
    if(!driver.equals(null)){
        driver.quit();
    }
}

Complete Code:

package stepDef;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import java.util.concurrent.TimeUnit;
public class AssertExample {
   public static WebDriver driver=null;
    @BeforeMethod
    public void setUp() {
        WebDriverManager.chromedriver().version("83.0.4103.61").setup();
        driver = new ChromeDriver();
        driver.get("http://newtours.demoaut.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }
    //@Test
    public void LoginVerifyWithHardAssert() throws InterruptedException {
        driver.findElement(By.xpath("//input[@name='userName']")).sendKeys("mercury");
        driver.findElement(By.xpath("//input[@name='password']")).sendKeys("mercury");
        driver.findElement(By.xpath("//input[@name='login']")).click();
        Thread.sleep(5000);
        String pageTitle = driver.getTitle();
        System.out.println("Page Title: " + pageTitle);
        Assert.assertEquals(pageTitle, "Find a Flight: Mercury Tours:-Hard 1");
        driver.findElement(By.xpath("//input[@name='findFlights']")).click();
        String selectPageTitle = driver.getTitle();
        System.out.println("Page Title: " + selectPageTitle);
        Assert.assertEquals(selectPageTitle, "Select a Flight: Mercury Tours-Hard 2");
        driver.findElement(By.xpath("//input[@name='reserveFlights']")).click();
        driver.findElement(By.xpath("//input[@name='buyFlights']")).click();
        Thread.sleep(7000);
        driver.close();
        System.out.println("Test Completed!");
    }
  @Test
    public void BookFlightVerifyWithSoftAssert() throws InterruptedException {
        driver.findElement(By.xpath("//input[@name='userName']")).sendKeys("mercury");
        driver.findElement(By.xpath("//input[@name='password']")).sendKeys("mercury");
        driver.findElement(By.xpath("//input[@name='login']")).click();
        SoftAssert soft = new SoftAssert();
        Thread.sleep(5000);
        String pageTitle = driver.getTitle();
        System.out.println("Page Title: " + pageTitle);
        soft.assertEquals(pageTitle, "Select a Flight: Mercury Tours1");
        driver.findElement(By.xpath("//input[@name='findFlights']")).click();
        String selectPageTitle = driver.getTitle();
        System.out.println("Page Title: " + selectPageTitle);
        soft.assertEquals(selectPageTitle, "Select a Flight: Mercury Tours2");
        driver.findElement(By.xpath("//input[@name='reserveFlights']")).click();
        driver.findElement(By.xpath("//input[@name='buyFlights']")).click();
        Thread.sleep(7000);
        String confirmationPageTitle = driver.getTitle();
        System.out.println("Confirmation Page Title: "+confirmationPageTitle);
        soft.assertEquals(confirmationPageTitle, "");
        driver.close();
        System.out.println("Test Completed!");
        soft.assertAll();
    }
    @AfterTest
    public void closeSetUp(){
        if(!driver.equals(null)){
            driver.quit();
        }
    }
}

Refer below console output.

Soft Assertion Console error

Summary of Steps for Soft Assertions:

Summary Soft Assertion

Great ! you have completed completed tutorial on Soft Assert and Hard Assert. We hope you enjoyed it and learned. Let us know if you face any issue or if you really like our tutorial then share your feedback on thoughcoders2020@gmail.com. You may also join us on Facebook & LinkedIn!

Write A Comment