Selenium

How to Use Assert in Selenium

Selenium is used to automate tests for web applications. It can be integrated with test automation frameworks like TestNG to infer if a particular test case is a pass or fail.

We normally execute many tests using Selenium in a cycle. However, to conclude on the outcome of the test case, we need to use assertions. Thus, they help to determine if the expected and actual results in a test are the same. In case they differ, we can say that the test has failed.

Precondition

To work with Selenium along with TestNG, we need to add the below TestNG Jar to our project from the Maven repository:

https://mvnrepository.com/artifact/org.testng/testng

One of the most commonly used methods in assertion is in the below format:

Assert.assert method (actual result, expected result)

The actual result is the outcome that we get in the application we are testing and the expected result points to the requirement that states how the test application should work.

Illustration Scenario

Let us take an example where we will validate the text – The Selenium Browser Automation Project – on a webpage.

Url: https://www.selenium.dev/documentation/

Implementation
Let us have a Java file NewTest.java with the below code.

import org.testng.Assert;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class NewTest {
    @Test
    public void textVerification() {
        System.setProperty("webdriver.chrome.driver", "chromedriver");
        WebDriver brw = new ChromeDriver();
        brw.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        brw.get("https://www.selenium.dev/documentation/");
        String text = brw.findElement(By.tagName("h1")).getText();
        String requiredText = "Selenium Projects";
        Assert.assertEquals(text, requiredText);
    }
}

After completing the implementation, we need to save and run this Java file.

In the above code, lines 2 to 7 are the Java imports needed for Selenium, TestNG, and Assertion.

Lines 9 and 11, describe the name of the class and the test method – textVerification(). Line 10 is for the TestNG @Test annotation.

In line 12, we are instructing the Selenium WebDriver to search for the chrome driver executable file within the project directory.

In lines 13 to 15, we are first creating a Selenium WebDriver object and storing it in the brw variable. Then, we have introduced an implicit wait for the WebDriver object for three seconds. Lastly, we are opening the https://www.selenium.dev/documentation/ application in the Chrome browser.

In line 16, we have identified the searched element with the tagname locator. Then stored its text in a variable(text) using the getText() method.

In line 17, we have stored text that we are expected to obtain in the application – Selenium Projects – using the requiredText variable.

We have incorporated assertion in our code (line 18) to verify the actual and expected outcome of the application using the assert method Assert.assetEquals().

We have passed two strings – actual (The Selenium Browser Automation Projects)

and expected text (Selenium Projects) as parameters to the assertEquals() method. It compares if both of them are equal.

Output
On running the above code, we have obtained the AssertionError. This is because the expected and actual texts are not similar. Ultimately, the textVerification text method is shown as FAILED.

Assertion with Message

In the example discussed above, we have obtained an AssertionError in the output along with the expected and actual texts. However, we can make the output more customized by adding an appropriate message in the assert method.

This can be done by incorporating another parameter in the assert method in the below format:

Assert.assert method (actual result, expected result, message)

The actual result is the outcome that we get in the application we are testing and the expected result points to the requirement that states how the test application should work. The message is the output string that shall appear in the console when we encounter a failure.

Implementation
Let us modify the existing NewTest.java file to add message in assertion.

import org.testng.Assert;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class NewTest {
    @Test
    public void textVerification() {
        System.setProperty("webdriver.chrome.driver", "chromedriver");
        WebDriver brw = new ChromeDriver();
        brw.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        brw.get("https://www.selenium.dev/documentation/");
        String text = brw.findElement(By.tagName("h1")).getText();
        String requiredText = "Selenium Projects";
        Assert.assertEquals
(text, requiredText, "Actual and Expected Texts are different");
    }
}

Post the implementation, we require to save and run this Java file.

We have incorporated assertion in our code (line 18) using the assert method Assert.assetEquals().

We have passed three strings as parameters to the assertEquals() method:-

  • Actual text which is – The Selenium Browser Automation Projects
  • Expected text which is – Selenium Projects
  • Message text which is Actual and Expected Texts are different

Output
On running the above code, we have obtained the AssertionError along with the message – Actual and Expected Texts are different. This is because the expected and actual texts are not similar. Ultimately, the textVerification text method is shown as FAILED.

Assertion Types

The names of assertion types include:

  • Soft Assertion
  • Hard Assertion

Soft Assertion

In a soft assertion, execution continues even if we encounter an assertion failure in a step in the middle of test execution. When a Selenium test is integrated with TestNG, a soft assertion is not available automatically.

We need to add the import the statement org.testng.asserts.Softassert in Java to include soft assertions. A soft assertion (also called verify) is generally used if a have a less critical validation is included in our test.

In case it fails, we ignore that failure for the time being and continue with the rest of the test. Once the execution is completed, we would get all the test results and exceptions by adding the assertAll() method.

In soft assertion, we need to create an object of SoftAssert class (having access only within the test method where it is created) to work with the assert methods.

Let us add one more validation to our illustration scenario. We shall also verify if the text – The Selenium Browser Automation Projects is not null.

Implementation
Let us have a Java file AssertionSoft.java with the below code.

import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class AssertionSoft {
    @Test
    public void textVerification() {
        System.setProperty("webdriver.chrome.driver", "chromedriver");
        WebDriver brw = new ChromeDriver();
        brw.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        brw.get("https://www.selenium.dev/documentation/");
        SoftAssert s = new SoftAssert();
        String text = brw.findElement(By.tagName("h1")).getText();
        String requiredText = "Selenium Projects";
        s.assertEquals(text, requiredText);
        s.assertNull(text);
        brw.quit();
        s.assertAll();

    }
}

After completing the implementation, we need to save and run this Java file.

In the above implementation, we have added the soft assertion import statement in line 3 and created an object of the SoftAssert in line 16.

We have incorporated soft assertions in our code (lines 19, 20, and 22) with the help of the assert methods assertEquals() and assertNull().

For assertEquals(), we have passed two strings – actual (The Selenium Browser Automation Projects!) and expected (Selenium Projects) texts as parameters to the assertEquals method. It compares if both of them are equal.

For assertNull(), we have passed the text obtained from our searched element as a parameter to check if it is null.

Finally, we have added the assertAll() method to get the details of all the exceptions and pass/fail status at the end of the execution.

Output
On running the above code, we have obtained all the AssertionErrors. Also, it should be noted that after the failure of the first assert method(assertEquals()), the execution has not halted and the next assert method(assertNull()) has also been executed.

Besides, the details of all the errors along with the expected and actual outcomes are also recorded. Ultimately, the textVerification text method is shown as FAILED.

Hard Assertion

In a hard assertion, execution comes to an end if we encounter an assertion failure in a step in the middle of test execution. Thus, all the following assertions (after the failed one) and steps are not verified. In TestNG, hard assertions are available by default.

A hard assertion is used for checking a critical functionality. If that verification fails, there is no need to continue with the execution anymore.

Let us apply the same verifications described previously using hard assertion.

Implementation
Let us have a Java file AssertionHard.java with the below code.

import org.testng.Assert;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class AssertionHard {
    @Test
    public void textVerification() {
        System.setProperty("webdriver.chrome.driver", "chromedriver");
        WebDriver brw = new ChromeDriver();
        brw.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        brw.get("https://www.selenium.dev/documentation/");
        String text = brw.findElement(By.tagName("h1")).getText();
        String requiredText = "Selenium Projects";
        Assert.assertEquals(text, requiredText);
        Assert.assertNull(text);
        brw.quit();

    }
}

After completing the implementation, we need to save and run this Java file.

We have incorporated hard assertions in our code (lines 18 to 19) with the help of the assert methods assertEquals() and assertNull().

For assertEquals(), we have passed two strings – actual (The Selenium Browser Automation Projects) and expected (Selenium Projects) texts as parameters to the assertEquals() method. It compares if both of them are equal.

For assertNull(), we have passed the text obtained from our searched element as a parameter to check if it is null.

Output
On running the above code, we have obtained an AssertionError. Also, it should be noted that after the failure of the first assert method(assertEquals()), the execution has stopped and the next assert method(assertNull()) has not been executed.

Ultimately, the textVerification text method is shown as FAILED.

Conclusion

Thus, we have seen how to use assertion in Selenium. We have also explored how to add a message to an assert method. This approach gives a more detailed view of an exception in the console. Also, we have discussed two types of assertions – hard and soft.

About the author

Debomita Bhattacharjee