How to Create TestNG Test Case in Selenium

Harsh S.
By
Harsh S.
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale...
10 Min Read
TestNG Test Case Using Selenium Webdriver

In our previous blog posts on the TestNG framework, we covered the installation of TestNG in Eclipse and discussed the various TestNG annotations available for the Selenium Webdriver. If you are planning to learn Selenium Webdriver using TestNG, it would be worth reading these posts. In case you already know TestNG then you would be aware that it works in a proper sequence with entities like the test cases, test suites, test groups, etc. In today’s post, we’ll show how to create a TestNG test case using Selenium Webdriver.

Simple steps to create test cases using TestNG

In this tutorial, we’ll create a demo TestNG project in Eclipse and add the Selenium Webdriver standalone jar to demonstrate the TestNG test case execution. You must note that every TestNG project can have an associated <TestNG.XML> file that outlines the structure of the test cases. It allows you to group multiple test cases into a single test suite. For your reference, a simple version of the <TestNG.XML> is as follows.

Define the TestNG test case

A TestNG test case is typically defined by a class that contains one or more methods. Each method in the class represents a single test case. The methods in the class are annotated with TestNG annotations that specify the behavior of the test case.

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Demo suite 1" verbose="1" >
  <test name="Demo test 1" >
    <classes>
      <class name="com.techbeamers.TestA"/>
      <class name="com.techbeamers.TestB"/>
      <class name="com.techbeamers.TestC"/>
    </classes>
 </test>
</suite>

We mentioned the <TestNG.XML> just because you might need to modify this file to enable/disable test cases. Also, it is one of the typical questions asked during test automation interviews.

The next important thing you might be wondering is the scenario we are going to automate while writing the TestNG case. So here are the details of the use case we’ll cover in this demo project.

Test cases for automation

You are supposed to perform the following steps in the course of creating your first TestNG test case.

  • Create a TestNG test case class and instantiate the Firefox Webdriver Object.
  • Start the Firefox web browser and navigate to the URL (http://newtours.demoaut.com/).
  • Fill the user name field with “test”.
  • Fill the password field with “test”.
  • Click on the sign-in link for login.

Steps to create TestNG test cases for Selenium

Let’s follow each of the steps one by one. We assume that you have a working installation of the Eclipse IDE and the TestNG plugin. If any of these are missing, you might consider reading these Selenium TestNG tutorials.

Step:1 Create a Java project in Eclipse

You need to start the Eclipse IDE and choose to create a new Java project to write the first TestNG test case. Press next and take clues from the attached screenshot.

Create Eclipse Java Project to Write a TestNG Test Case
Create Eclipse Java Project to Write a TestNG Test Case

Name the new TestNG project as the <TestNGSeleniumDemo> and press the Finish button for successful project creation.

Create a New Java Project in Eclipse
New Java Project to Write a TestNG Test Case

Step:2 Add the <TestNG> library to your project

Here are the steps to introduce the <TestNG> library.

Right-click on the project icon to open the context menu and click the “Build Path >> Add Library” option.

It’ll open up a dialog listing all the installed libraries. Choose the <TestNG> option to add it to your project.

Add TestNG Library to Write a TestNG Test Case
Add TestNG Library to Write a TestNG Test Case

Step:3 Create a new package

Right-click on the project icon and select the “New” option to create a package as <com.techbeamers.testng>.

Step:4 Adding a TestNG class

Right-click on the newly created package and select New >> Other.

Adding TestNG Test Case Class
Adding TestNG Test Case Class

You’ll now see a TestNG class dialog like the one shown below.

  • Here you must give a name to the new TestNG class as <SeleniumWebdriverTest>.
  • Then, select the <BeforeMethod> and <AfterMethod> checkboxes available on the dialog box.
  • Finally, press the Finish button to create the class.
Select annotations for your eclipse project
Set TestNG Annotations for the TestNG Test Class

After this, Eclipse will auto-generate the TestNG class code. But there’ll be errors in the code because of missing package imports. We are giving you a solution to this issue. You must remember it as it is one of the crucial steps which you’ll need later as well.

Q: How will you fix the import errors for the missing packages?

It’s very easy to resolve such compile time issues.

  • Make sure you’ve added the related library into your projects like the TestNG library or the Selenium Webdriver standalone Jar.
  • You don’t need to remember the names of the required packages. Just press the CTRL+Shift+O keyboard shortcut. And it will automatically add the required imports to your code.
package com.techbeamers.testng;

public class SeleniumWebdriverTest {
  @Test
  public void f() {
  }
  @BeforeMethod
  public void beforeMethod() {
  }

  @AfterMethod
  public void afterMethod() {
  }
}
package com.techbeamers.testng;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class SeleniumWebdriverTest {
  @Test
  public void f() {}

  @BeforeMethod
  public void beforeMethod() {}

  @AfterMethod
  public void afterMethod() {}
}

Step:5 Add Selenium Webdriver standalone Jar to your project

You should be careful while adding the Selenium Webdriver jar file because the file must be compatible with the version of the browser (Firefox) you’ll use for testing. For this demo project, we’ve downloaded the latest version of the jar (2.53.0) file from the Selenium website. We’d the most recent version of the browser (i.e. Firefox 45) which works well with the downloaded jar file.

Here, you may ask why are we using the standalone API of the Selenium Webdriver.

The reason is straightforward and clearly explained below.

  • Using it eliminates the need for adding any other dependent library.
  • It directly works with the Firefox browser.
  • To run your tests with browsers like Chrome, you need to download/add their respective driver’s jar files.

Step:6 Write a TestNG test case script using Selenium

We’ve given the full source code of the TestNg test case script. You can directly copy it to your project’s <SeleniumWebdriverTest.java> file. You can change the name of this file, but then you would also need to make the same modifications in the below source code. Here we are automating the TestNG test case scenario mentioned earlier.

package com.techbeamers.testng;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class SeleniumWebdriverTest {

  WebDriver driver = new FirefoxDriver();

  @Test
  public void MyFirstTestNGTestCase() throws InterruptedException {
    String title = driver.getTitle();
    System.out.print("Current page title is : " + title);

    WebElement user = driver.findElement(By.name("userName"));
    user.sendKeys("test");
    WebElement pwd = driver.findElement(By.name("password"));
    pwd.sendKeys("test");
    WebElement signin = driver.findElement(By.name("login"));
    signin.click();

    Thread.sleep(1000);

    System.out.print("\n'SUCCESSFUL EXECUTION!!!");
  }

  @BeforeMethod
  public void startFireFox() {
    driver.manage().window().maximize();
    driver.get("http://newtours.demoaut.com/");
  }

  @AfterMethod
  public void cleaupProc() {
    System.out.print("\nBrowser close");
    driver.quit();
  }
}

Step:7 Run the TestNG Test Case and View the Report

You can easily run any of the TestNG test cases. Just right-click on the TestNG project icon, and click the “Run as >> TestNG Test” option to execute the script. Check out the below snapshot for more info.

How to Run the TestNG Test Case
How to Run the TestNG Test Case

When you run the test case, it creates a <test-output> folder which contains a folder named the <Default suite>. Here the TestNG project report is available in the <Default test.html> file. You can load the report in Eclipse by opening it in the web browser mode. For more clarity on viewing the test execution report, refer to the attached picture.

View Test Report
TestNG Test Execution Report

Before You Leave

We tried to reduce the complexity of the steps required to create a TestNG test case using Selenium Webdriver API. Additionally, we mentioned little tricks that can help you write effective test cases and resolve errors.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy testing,
TechBeamers.

Share This Article
Leave a Comment
Subscribe
Notify of
guest

0 Comments
Newest
Oldest
Inline Feedbacks
View all comments