selenium
  1. selenium-assertions

Assertions - ( Selenium WebDriver )

Assertions are an integral part of automated testing. They are used to check whether the actual result is equal to the expected result or not. In Selenium WebDriver, assertions are used to verify if the application behaves as expected.

Syntax

Below is the syntax to write an assertion in Selenium WebDriver using the TestNG framework.

Assert.assertEquals(actual, expected, message);

Example

Consider the following example of an assertion in Selenium WebDriver using TestNG framework.

import org.testng.Assert;
import org.testng.annotations.Test;

public class AssertionExample {
   @Test
   public void testExample() {
      String str1 = "Hello";
      String str2 = "Hello";
      String str3 = "World";
      String str4 = "World";
        
      //Asserts that str1 and str2 are equal
      Assert.assertEquals(str1, str2, "Strings str1 and str2 are not equal");
        
      //Asserts that str3 and str4 are equal
      Assert.assertEquals(str3, str4, "Strings str3 and str4 are not equal");
        
      //Asserts that str1 and str3 are not equal
      Assert.assertNotEquals(str1, str3, "Strings str1 and str3 are equal");
   }
}

Output

The output of the assertion example code will be:

PASSED: testExample

Explanation

In the above example, three assertions have been used with different types of conditions. The first assertion checks if the two strings str1 and str2 are equal. Since they are equal, the assertion passes.

The second assertion checks if the two strings str3 and str4 are equal. Since they are equal, the assertion passes.

The third assertion checks if str1 and str3 are not equal. Since they are not equal, the assertion passes.

If any of the assertions fail, the method will throw an AssertionError.

Use

Assertions are used to verify the expected behavior of an application in automated testing. Assertions help in verifying that the application under test is behaving as expected and is producing the expected results.

Important Points

  • Assertions help ensure the correctness of the application under test.
  • TestNG provides a variety of assertions that can be used in Selenium WebDriver.
  • Assertions should be used with a precise error message to make it easier for developers to debug failed assertions.
  • If an assertion fails, then the test case will fail, and the execution will stop.

Summary

Assertions are used to verify whether the actual result is equal to the expected result. They help in ensuring the correct behavior of the application under test. TestNG provides various assertions which can be used in Selenium WebDriver. If an assertion fails, then the test case fails, and the execution stops.

Published on: