Assertion in TestNG

TestNG assertions are the most common methods which are used to verify the condition. There are two types of assertion.

  • Hard Assert
  • Soft Assert

1. Hard Assert:

It makes the method as fail if assert condition gets failed and the remaining statements inside the method will be aborted. Hard Assert throws an AssertException immediately when an assert statement fails.
The drawback of Hard Assert is if assert condition gets failed then the remaining statements inside the test method will be aborted.

Let us see an example:

package testFramework;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class HardAssertTest {

  public WebDriver driver;

  @Test
  public void TestHardAssert() throws InterruptedException {
    driver = new FirefoxDriver();
    driver.get("https://blueimp.github.io/jQuery-File-Upload/");

    Assert.assertTrue(driver.findElement(By.cssSelector(".pull-left h1")).getText().equals("jQuery File Upload Demo"));
    Assert.assertEquals(driver.getTitle(), "jQuery File Upload Demo");

    driver.close();
  }
}


2. Soft Assert:

Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.

If there is an exception and you want to throw it then you need to use assertAll() method as a last statement in the @Test. If we forget to call assertAll() at the end of our test, the test will pass even if any assert objects threw exceptions. So we should remember to add assertAll().

Let us see an example:

package testFramework;

import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;

public class SoftAssertTest {

  @Test
  public void TestSoftAssert() throws InterruptedException {
    SoftAssert softAssert = new SoftAssert();
    System.out.println("Created an object of SoftAssert");
    softAssert.assertTrue(true);
    System.out.println("Set a pass condition");
    softAssert.assertFalse(true);
    System.out.println("Set a fail condtion");
    System.out.println("Even condition is failed, this step is executed due to soft assertion check point");
    softAssert.assertAll();
  }
}

 

Output:

[RemoteTestNG] detected TestNG version 6.14.2
Created an object of SoftAssert
Set a pass condition
Set a fail condtion
Even condition is failed, this step is executed
PASSED: TestSoftAssert

===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================