TestNG and Selenium: How to use TestNG with Selenium WebDriver to Automate Web Testing

In today’s fast-paced digital world, websites and web applications have become an integral part of businesses. As the usage of web applications increases, it becomes crucial for developers and testers to ensure that these applications work flawlessly across different platforms, browsers, and devices. Manual testing of web applications can be a tedious and time-consuming task, and it is prone to human errors. This is where automated testing comes into the picture.

Introduction to TestNG and Selenium

TestNG and Selenium WebDriver are two popular tools used for automated web testing. TestNG is a testing framework for Java that provides a wide range of features for testing applications, including annotations, assertions, and test reporting. Selenium WebDriver is a browser automation tool that enables testers to interact with web elements such as links, buttons, and forms, and perform actions like clicking, typing, and scrolling.

Using TestNG with Selenium WebDriver provides a powerful combination for automated web testing. By writing tests in TestNG, you can organize and execute tests more efficiently, while Selenium WebDriver allows you to interact with web elements and simulate user actions. Together, they can help you create robust and reliable automated tests for your web applications.

Let’s consider an example of an e-commerce website that sells clothes online. The website has different pages for product categories such as shirts, pants, and shoes. Each page has multiple products with their images, names, and prices displayed. The website also has a search bar where customers can search for products by name or keyword.

Now, imagine you are a tester responsible for ensuring that this website works correctly. You need to test different scenarios such as searching for a product, adding it to the cart, and checking out. With manual testing, you would have to perform these actions manually, which can be time-consuming and error-prone.

However, by using TestNG with Selenium WebDriver, you can automate these tests and run them repeatedly. You can write test methods that simulate user actions such as entering text in the search bar, clicking on a product, adding it to the cart, and checking out. You can also use TestNG annotations to organize your tests and execute them in a specific order. The result is a more efficient and reliable testing process.

Setting up TestNG and Selenium WebDriver

Before we start writing automated tests using TestNG and Selenium WebDriver, we need to set up our environment. This involves installing TestNG and Selenium WebDriver and configuring our project to use them.

1. Installing TestNG:

To install TestNG, we can use a build tool like Maven or Gradle. We can also download the TestNG jar files and add them to our project manually. Let’s see how to install TestNG using Maven.

I. Create a new Maven project in Eclipse or IntelliJ.

II. In the pom.xml file, add the following dependency for TestNG:

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.7.1</version>
    <scope>test</scope>
</dependency>

III. Save the pom.xml file, and Maven will download and install the TestNG dependency.

2. Installing Selenium WebDriver:

To install Selenium WebDriver, we need to download the WebDriver executable for the browser we want to test. For example, if we want to test in Chrome, we need to download the chromedriver executable.

Read our blog Selenium: The Ultimate Guide To Automated Testing for detailed step by step guide to setup and install selenium webdriver.

3. Configuring the Project:

Once we have installed TestNG and Selenium WebDriver, we need to configure our project to use them. We need to create a TestNG XML file that specifies which classes and methods to run.

I. Create a new TestNG XML file in the project.

II. In the XML file, specify the test classes and methods that you want to run. For example:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="Test Suite">
  <test name="Test">
    <classes>
      <class name="com.example.tests.TestClass"/>
    </classes>
  </test>
</suite>

III. Save the TestNG XML file.

Writing and running TestNG Tests with Selenium WebDriver

Now that we have set up our environment, let’s start writing automated tests using TestNG and Selenium WebDriver.

I. Creating a Test Class:
To create a TestNG test class, we need to create a Java class and annotate it with @Test.
Let’s create a simple test class that launches the Chrome browser and navigates to a website.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class MyTest {

   @Test
   public void testGoogle() {
      
      // Create a new instance of the ChromeDriver
      WebDriver driver = new ChromeDriver();
      
      // Navigate to Google
      driver.get("https://www.google.com");
      
      // Close the browser
      driver.quit();
   }
}

II. Running the Test:
To run the test, we need to run the TestNG XML file that we created earlier. We can do this by right-clicking on the XML file and selecting “Run As” -> “TestNG Suite”. This will execute all the tests specified in the XML file.

TestNG Annotations

TestNG provides several annotations that we can use to control the flow and behavior of our tests. Let’s take a look at some of the most commonly used annotations in Selenium WebDriver tests.

I. @Test:
@Test is a TestNG annotation used to mark a method as a test method. When TestNG runs tests, it looks for methods annotated with @Test and executes them as tests.

@Test
public void testLoginWithValidCredentials() {
   // test code here
}

II. @BeforeMethod and @AfterMethod:
These annotations are used to define methods that will be executed before and after each test method. We can use these annotations to set up and close down our test environment. For example, we can use @BeforeMethod to launch the browser and @AfterMethod to close it.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class MyTest {

   WebDriver driver;

   @BeforeMethod
   public void setUp() {

      // Create a new instance of the ChromeDriver
      driver = new ChromeDriver();
   }

   @Test
   public void testGoogle() {
      // Navigate to Google
      driver.get("https://www.google.com");
      
      // Check that the title of the page contains "Google"
      Assert.assertTrue(driver.getTitle().contains("Google"));
   }

   @AfterMethod
   public void closeDown() {
      // Close the browser
      driver.quit();
   }
}

III. @BeforeTest and @AfterTest:
These annotations are used to define methods that will be executed before and after all the test methods in a TestNG test class. We can use these annotations to set up and close down our test environment at the test class level.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class MyTest {

   WebDriver driver;

   @BeforeTest
   public void setUp() {

      // Create a new instance of the ChromeDriver
      driver = new ChromeDriver();
   }

   @Test
   public void testGoogle() {
      // Navigate to Google
      driver.get("https://www.google.com");
      
      // Check that the title of the page contains "Google"
      Assert.assertTrue(driver.getTitle().contains("Google"));
   }

   @AfterTest
   public void closeDown() {
      // Close the browser
      driver.quit();
   }
}

IV. @Parameters:
This annotation is used to pass parameters to our test methods. We can use this annotation to pass different values to our tests and run them with different input data.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class MyTest {

   @Test
   @Parameters("searchTerm")
   public void testSearch(String searchTerm) {
      // Create a new instance of the ChromeDriver
      WebDriver driver = new ChromeDriver();
      
      // Navigate to the website
      driver.get("https://www.google.com");
      
      // Enter the search term
      driver.findElement(By.id("search")).sendKeys(searchTerm);
      driver.findElement(By.id("submit")).click();
      
      // Check that the search results contain the search term
      Assert.assertTrue(driver.getPageSource().contains(searchTerm));
      
      // Close the browser
      driver.quit();
   }
}

In above example, we are using the @Parameters annotation to pass the “searchTerm” parameter to our test method. We can define the values for this parameter in our testng.xml file as follows:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="MyTestSuite" verbose="1">
  <test name="MyTest" >
    <parameter name="searchTerm" value="TestNG" />
    <classes>
      <class name="MyTest" />
    </classes>
  </test>
</suite>

V. @DataProvider:
This annotation is used to provide test data to our test methods. We can use this annotation to run our tests with different sets of input data.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class MyTest {

   @Test(dataProvider = "searchTerms")
   public void testSearch(String searchTerm) {
      
      // Create a new instance of the ChromeDriver
      WebDriver driver = new ChromeDriver();
      
      // Navigate to the website
      driver.get("https://www.google.com");
      
      // Enter the search term
      driver.findElement(By.id("search")).sendKeys(searchTerm);
      driver.findElement(By.id("submit")).click();
      
      // Check that the search results contain the search term
      Assert.assertTrue(driver.getPageSource().contains(searchTerm));
      
      // Close the browser
      driver.quit();
   }

   @DataProvider(name = "searchTerms")
   public Object[][] searchData() {
      return new Object[][] {{"TestNG"}, {"Selenium"}, {"WebDriver"}};
   }
}

In above example, we are using the @DataProvider annotation to provide the search terms for our testSearch method. The searchData method returns an array of arrays containing the different search terms we want to test.

These are some of the most commonly used annotations in TestNG tests with Selenium WebDriver. We can use them to control the flow and behavior of our tests and make them more efficient and maintainable.

You Might Like: