Assertions in Selenium Using Junit and TestNG Frameworks

All that You need to know about Assertions in Selenium Using Junit and TestNG frameworks:

An assertion is used to compare the actual result of an application with the expected result.

The assertion is considered to be met if the actual result of an application matches with that of the expected result.

A test case is considered to be passed only if all the assertions have been met. Assertions in Selenium can be handled by pre-defined methods of Junit and TestNG frameworks, which will be explained in detail in this article.

Assertions in Selenium

Types of Assertions in Selenium

There are two types of assertions in Selenium and the categorization is dependent on how the assertion behaves after a condition is pass or fail.

Enlisted below are different the Types of Assertions in Selenium:

Hard Assertions

A hard assertion does not continue with execution until the assertion condition is met.

Hard assertions usually throw an Assertion Error whenever an assertion condition has not been met. The test case will be immediately marked as Failed when a hard assertion condition fails.

Soft Assertions

A soft assertion continues with test execution even if the assertion condition is not met. Usually, Soft Assertion does not throw any error when the assertion condition fails but continues with the next step of the test case.

Junit Assert Methods

The various types of Junit Assert methods are explained below in detail.

#1) assertEquals

assertequals method compares the expected result with that of the actual result. It throws an AssertionError if the expected result does not match with that of the actual result and terminates the program execution at assert equals method.

Syntax:

public static void assertEquals(String expected, String actual)

Example:

String expected = “https://www.google.com”;

String actualURL= “https://www.google.com”;

Assert.assertEquals(expected, actualURL);

#2) assertTrue

asserttrue method asserts that a specified condition is true.

It takes in two parameters i.e. one is the message and the other is the condition against which the assertion needs to be applied. It throws an AssertionError if the condition passed to the asserttrue method is not satisfied.

Syntax:

public static void assertTrue(java.lang.String message, boolean condition)

message – Message to be displayed in case of an Assertion Error.
condition – Condition against which the assertion needs to be applied.

Example:

Assert.assertTrue(“Assert True test message”, true);

#3) assertFalse

assert false method asserts that a specified condition is false.

It takes in two parameters, i.e. one is the message and the other is the condition against which the assertion needs to be applied. It throws an AssertionError if the condition passed to the assertfalse method is not satisfied.

Syntax:

public static void assertFalse(java.lang.String message, boolean condition)

message – Message to be displayed in case of an Assertion Error.
condition – Condition against which the assertion needs to be applied.

Example:

Assert.assertFalse(“Assert false test message” false);

#4) assertNull

assert null is used to verify if the provided object contains a null value. It takes an object as the parameter and throws an AssertionError if the provided object does not hold a null value.

Syntax:

public static void assertNull(Object object)

Example:

DemoClass demo = new DemoClass();
Assert.assertNull(demo);

#5) assertNotNull

assert not null is used to verify that a provided object does not hold a null value. It takes an object as the parameter and throws an AssertionError if the provided object does not contain a null value.

Syntax:

public static void assertNotNull(Object object)

Example:

DemoClass demo = new DemoClass();
Assert.assertNotNull(demo);


#6) assertSame

assert same method checks if two objects provided as parameters refer to the same object. It throws an AssertionError if the provided objects do not refer to the same object with the message provided.

Please note that Assert same compares the references of objects only, but not the actual values.

Syntax:

public static void assertSame(String message, Object expected,Object actual)

Example:

DemoClass1 demo1 = new DemoClass1();
DemoClass2 demo2= new DemoClass2();
Assert.assertSame(“Two objects are equal”, demo1, demo2);

#7) assertNotSame

assert not same verifies that two objects are not equal. If two objects to refer to the same object, then an AssertionError will be thrown.

Please note that the assert not same method compares the references of objects and not the values present in the objects.

Syntax:

public static void assertNotSame(String message, Object expected, Object actual)

Example:

DemoClass1 demo1 = new DemoClass1();
DemoClass2 demo2= new DemoClass2();
Assert.assertNotSame(“Two objects are not equal”, demo1, demo2);

#8) assertArrayEquals

assert equals verifies that two object arrays are equal. If both the arrays hold null values, then they are being considered as equal. This method throws an AssertionError with the message provided if both the object arrays are not considered equal.

Syntax:

public static void assertArrayEquals(String message, Object[] expected, Object[] actual)

message – Message to be displayed in case of an assertion error.
expected – Array of objects.
actual – Array of objects.

Example:

String[] expected = {“Mango”,”Apple”,”Banana”}

String[] actual = {“ Mango”,”Apple”,”Banana”}

Assert.assertArrayEquals(expected,actual);

TestNG Assert Methods

TestNG Assert methods will be the same as the Junit assertion methods that are discussed above. The major difference between Junit and TestNG assertion methods come in the way of handling assertions.

TestNG provides more advanced assertion handling techniques such as dependent classes, Group Test, Parameterized tests etc.

Sample Programs for Assertions

Assert Equals:

package Demo;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AssertionDemo {
public static void main(String[] args) throws InterruptedException{
String sValue = "Assert Equals Test";
Assert.assertEquals("Assert Equals Test", sValue);
System.out.println("Test Passed");
}
}

Code Explanation:

The above code demonstrates the use of AssertEquals method in simple terms.

  • As discussed earlier, assert equals takes in two parameters i.e. expected result and actual result. If the expected result does not match with that of the actual result, then an assertion error will be thrown and the program execution will terminate at assert equals method.
  • The above code compares the user-defined string value to the expected string value.
  • Please note that in real time, the actual result will be a user defined operation for which the value will be fetched at run time and passed as a parameter to the assert equals method.

Assert True:

package Demo;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AssertionsDemo1 {
public static void main(String[] args) throws InterruptedException{
String expectedTitle = "Google";
System.setProperty("webdriver.gecko.driver","D:\\Data_Personal\\Demo\\geckodriver-v0.23.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Assert.assertTrue("Title does not match", expectedTitle.equals(driver.getTitle()));
driver.close();
}
}

Code Explanation:

The above code demonstrates the usage of the assertTrue method.

  • We are initially passing the expected page title onto a variable. We are then instantiating an object of firefox driver and navigating it to the web page – https://www.google.com
  • Later, Using assertsTrue method we are comparing the opened page title with that of the expected page title. If the opened page title does not match with that of the expected title, then an assertion error will be thrown and program execution will be terminated at the assertTrue method.
  • The above code will be executed successfully only when the actual page title matches with that of the expected page title.

Assert False:

package Demo;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AssertionsDemo1 {
public static void main(String[] args) throws InterruptedException{
String expectedTitle = "Google1";
System.setProperty("webdriver.gecko.driver","D:\\Data_Personal\\Demo\\geckodriver-v0.23.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Assert.assertFalse("Title does match", expectedTitle.equals(driver.getTitle()));
driver.close();
}
}

Code Explanation:

The above code demonstrates the usage of the assertfalse method.

  • We are initially passing the expected page title onto a variable and then instantiating an object of the firefox driver and navigating to the web page – https://www.google.com
  • Later, using the assertfalse method we are comparing the opened page title with that of the expected page title. If the opened page title matches with that of the expected title, then an assertion error will be thrown and the program execution will be terminated at the assert false method.
  • The above code will be executed successfully only when the actual page title does not match with that of the expected page title.

End to end code for Assertions

Given below is a sample end to end code for Assertions. We have used the following scenario for simplicity purpose.

Scenario:

  • Open the web page: https://www.google.com on the Firefox browser.
  • Verify if the opened page title is equivalent to that of expected page title using the asserttrue method.
  • On the search textbox, enter the search keyword: selenium.
  • Hit the Enter button on the keyboard.
  • Verify if the opened page title on the search results page is equivalent to that of the expected page title using the assertequals method and assertfalse method.
  • Close the browser.

Sample Code:

packageDemo;

importorg.junit.Assert;
importorg.openqa.selenium.By;
importorg.openqa.selenium.Keys;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
public class AssertionsDemo {
public static void main(String args[]) throws InterruptedException
{
String expectedTitle = "Google";
String expectedText = "selenium - Google Search";
System.setProperty("webdriver.gecko.driver","D:\\Data_Personal\\Demo\\geckodriver-v0.23.0-win64\\geckodriver.exe");
// Open the web page https://www.google.com using firefox browser
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");

// Validate if actual web page title matches with that of expected title using assert true method
System.out.println("Assert true method validation");
Assert.assertTrue("Title does not match", expectedTitle.equals(driver.getTitle()));

// Enter the keyword selenium on the search textbox
WebElementsearchBox = driver.findElement(By.xpath("//*[@name='q']"));
searchBox.sendKeys("selenium");
searchBox.sendKeys(Keys.ENTER);
Thread.sleep(8000);

// Validate the actual page title with expected page title using assert equals method
System.out.println("Assert equals method validation");
Assert.assertEquals(expectedText, driver.getTitle());

// Page title validation using assert false method
System.out.println("Assert false method validation");
Assert.assertFalse("Title does match", expectedTitle.equals(driver.getTitle()));

// Close the current browser
driver.close();
}
}

Code output:

Initially, the Firefox browser window will be opened with the web page: https://www.google.com. Asserttrue method will verify if the opened page title matches with that of the expected page title – Google.

Google Home Page

The script will enter the search keyword as selenium and hit the enter button.

Search on Google

Assertfalse and assertequals methods compare if the actual page title of the search results screen matches with that of the expected title – ‘selenium – Google Search’. The browser will then be closed through driver.close method.

Assertions Demo

Console Output:

The text given below will be the console output on Eclipse IDE

Console Output

Conclusion

We can conclude this article on Assertions in Selenium with the below pointers:

  • An assertion is used to compare the actual result of an application with the expected result.
  • A test case is considered to be passed only if all the assertions have been met.
  • AssertEquals method compares the expected result with that of the actual result. It throws an AssertionError if the expected result does not match with that of the actual result and terminates the program execution at the assertequals method.
  • AssertTrue method asserts that a specified condition is true. It throws an AssertionError if the condition passed to the asserttrue method is not satisfied.
  • AssertFalse method asserts that a specified condition is false. It throws an AssertionError if the condition passed to assert false method is not satisfied.
  • AssertEquals, AssertTrue, and AssertFalse methods are the most commonly used assertions in selenium.

Hope this article would have enriched your knowledge on Assertions in Selenium!!