TestNG – 5 || Understand Assertion in TestNG.

The Assertion in TestNG decides the Pass/Fail status of individual Test Methods. Java Assertion is mainly used to take decisions at the code level during execution. Based on that, the flow of the program would be decided.

This can be implemented using the Assert Class or assert keyword. This is not just related to TestNG. It can be used in programs as well for error handling or to avoid error at run time. But, this has been used mostly while working in TestNG Framework.

Assertion in TestNG

Assert in main() method

  • There are two important points to be considered while using assert:
    • By default, assert remains disabled in the Java. So, just writing code is not enough to run assert in the program.
    • Assert would only work using a command line argument while using in normal programs having main().
/**
 * @author ashok.kumar
 *
 */
public class AssertionUse {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int currentNumber=5;
		assert currentNumber >= 6:"User number is incorrect.";
		System.out.println("test completed.");
	}
}

In the above program observe that condition is false and should throw an error while execution. If we directly run the program using Eclipse or try to run it without asserting enabled, it won’t give any error or exception.

Below are the steps to execute the any program on command prompt:
1. Copy the entire code and paste it new Word or notepad Document.
2. Save the document with the Class name, example, “AssertionUse.java
3. Open the command prompt.
4. Locate folder which contains AssertionUse.java file.
5. type, javac AssertionUse.java and press Enter.
6. type, java AssertionUse and press Enter.
Now, to run the program with enabled assert feature replace point #6 with below line:
6. type, java -ea AssertionUse and press Enter.

Assertion in TestNG

In TestNG, assertions applied on Test Method level. Observe the below code, here we have used assertEquals method of Assert Class. There are two variations present for assertEquals method:

  • Assert.assertEquals(<actualResult>, <expectedResult>);
  • Assert.assertEquals(<actualResult>, <expectedResult>,”<errorMessage”>);

<actualResult> and <expectedResult>: could be String, int, Boolean, any type of array, object.

<errorMessage>: Any message in String format to display when Assertion gets failed.

  • Most commonly used assertions:
    • assertEquals
    • assertNotEquals
    • assertTrue
    • assertFalse
    • assertNull
    • assertNotNull
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author ashok.kumar
 *
 */
public class SampleAssertion {
	
	@Test
	public void LaunchBrowser()
	{
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		driver.get("http://google.com");
		System.out.println("First URL Launched.");
		
		String currentBrowserTitle=driver.getTitle();
		String expectedResult="google";
		
		Assert.assertEquals(currentBrowserTitle, expectedResult);
		
// Click on Search field and search any string.
driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys("allinoneblogs"+Keys.ENTER);

	}
	
	@Test
	public void LaunchBrowser2()
	{
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		driver.get("http://google.com");
		System.out.println("Second URL Launched");
		
		String currentBrowserTitle=driver.getTitle();
		String expectedResult="Google";
		
		Assert.assertEquals(currentBrowserTitle, expectedResult);
	}
	
	@Test(description="Assert with error message.")
	public void LaunchBrowser3()
	{
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		driver.get("http://google.com");
		System.out.println("Second URL Launched");
		
		String currentBrowserTitle=driver.getTitle();
		String expectedResult="Gmail";
		
		Assert.assertEquals(currentBrowserTitle, expectedResult,"Browser tile mismatch.");
	}
}

Hard Assertion

Note, rest of the code in a particular Test Method doesn’t get executed if assertion gets failed. In the above example, for the first test method “LaunchBrowser()“, observe that there was a code snippet to click on the search field and search any string as mentioned below:

// Click on Search field and search any string.
driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys("allinoneblogs"+Keys.ENTER);

Currently, the above line of code doesn’t get executed if the result of assertEquals() is FAIL. This process is called HARD Assertion.

Soft Assertion

There are scenarios where we want that rest of the code get execute even assertion gets failed. To achieve this we have to use SoftAssert Class.

import java.awt.RenderingHints.Key;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;

/**
 * @author ashok.kumar
 *
 */
public class VerifyAssertion {
	
	@Test
	public void LaunchBrowser()
	{
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		driver.get("http://google.com");
		System.out.println("First URL Launched.");
		
		String currentBrowserTitle=driver.getTitle();
		String expectedResult="google";
		
		SoftAssert softAssert =new SoftAssert();
		
		softAssert.assertEquals(currentBrowserTitle, expectedResult);
		
		driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys("allinoneblogs"+Keys.ENTER);
		
		softAssert.assertAll();
	}
}

In the SoftAssertion process, we could use multiple assertions in a single Test Method. At the end of the method, we have to use assertAll(). This method collates the result of all assertEquals() method. If anyone result fails the end result of the test method would also FAIL. To understand this refer below program:

import java.awt.RenderingHints.Key;

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

/**
 * 
 */

/**
 * @author ashok.kumar
 *
 */
public class VerifyAssertion {
	
	@Test
	public void LaunchBrowser()
	{
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		driver.get("http://google.com");
		System.out.println("First URL Launched.");
		
		String currentBrowserTitle=driver.getTitle();
		String expectedResult="google";
		
		SoftAssert softAssert =new SoftAssert();
		
		softAssert.assertEquals(currentBrowserTitle, expectedResult);
		
		String searchKey="allinoneblogs";
		driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys(searchKey+Keys.ENTER);
		currentBrowserTitle=driver.getTitle();
		
		softAssert.assertEquals(currentBrowserTitle, searchKey+" - Google Search");
		
		softAssert.assertAll();
	}
}
  • softAssert.assertEquals(currentBrowserTitle, expectedResult); : FAIL
  • softAssert.assertEquals(currentBrowserTitle, searchKey+” – Google Search”); : PASS
  • softAssert.assertAll(); : FAIL

Related Links:

Java Basics:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:

Excel:


4590total visits,18visits today

Leave a Reply

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