Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Complete Guide For Your First TestNG Automation Script

DZone's Guide to

A Complete Guide For Your First TestNG Automation Script

Take a look at how you can write an easy automation script and test it across browsers using LambdaTest.

· DevOps Zone ·
Free Resource

Learn how integrating security into DevOps to deliver "DevSecOps" requires changing mindsets, processes and technology.

The love of automation testers, TestNG, is a Java testing framework that can be used to drive a Selenium automation script. When it comes to automation, no one can compete with Selenium. If you are planning to dive into the field of automation testing, TestNG can be right for you.

For a beginner, it can be difficult to determine a good starting point, so in this blog, we have come up with a step-by-step method to assist you in getting started with your first automation test script.

For this, you need to set up an test automation environment for Selenium with Eclipse first and then go ahead with the script. Let’s do it.

Setting Up The Environment

Step 1: Download Java 8

First of all, download Java 8 or JDK1.8 and install it in your system. You can use this link to download Java 8.

After installing Java 8, set up the path. To do so, Go to Start→ Computer→ Right click → properties→ Advanced system settings → Environment variable→ New. After clicking on that you need to enter a variable name and path.

You’ll see the following screen in the "Environment variable" window.

Environment variable

Once you click on "New," you’ll see the following window. Enter "Path" as the variable name and enter the path where your JDK has been installed in the variable path. Let’s validate whether this is properly installed or not.

To do so, open the command window and type "javac".

You’ll see a window with all the details of JDK. If you get it, then it is properly installed; if not, then try again.

cmd window

Step 2: Download Eclipse

Next, download Eclipse and run it. You can use this link to download Eclipse. Select "Eclipse IDE for Java EE Developers" and install it.

Java EEE

Once you install it, an Eclipse IDE window will open for writing the script and it will look like this.

Console

Step 3: Download TestNG from Eclipse Marketplace

For this, Go to Help→ Eclipse Marketplace.

Eclipse Marketplace


Click "Install" on TestNG for Eclipse.

TestNG

And finish the process.

Step 4: Download Selenium 3.11.0

You can use this link to download the latest version of Selenium and its dependency files for jdk 3.11.0 using the link provided here.

Step 5: Create the project

Create a Java project by going to File→ New→ Other.

Select "Create a Java Project."

JAVA

Enter your project name. For mine, I am entering "FirstAutomationProject."
Note: Do not enter spaces in the name of the project.

Click "Open Perspective."

You’ll see that a new Java Project is created on the left side. Now, Click on "FirstAutomationProject." You’ll see src file. Right-click on it. Select new→ Other→ Create a new Java Package.


Click Finish.

Step 7: Create a New TestNG Class.

Create a new TestNG class under the package "newpack." Right-click newpack–> New –> Other

Check "@BeforeTest" and "@AfterTest." Once you click on "Finish," you’re all set to write your automation script.

A template TestNG code will open up like this.

Step 8: Import Selenium Jar Files in Dependency Files

Right click on FirstAutomationTest→ Import. Click on "Add external Jar" and add the Jar dependency files that you’ve downloaded above.

Select the .jar file that you’ve downloaded above.

Similarly, import the dependency files that you’ve downloaded from the link provided above.

Import lib files from the zip extracted dependency files.

Select all the files in the lib folder.

Once you import all the files, you’re all set to write the code.

Writing The Code

In the Eclipse window that you’re seeing now, write the following code. We are writing this code to verify the title of the webpage.

package newpack;   
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver; 
import org.testng.annotations.Test;   //comment the above line and uncomment below line to use Chrome //
import org.openqa.selenium.chrome.ChromeDriver; 
public class NewTest { WebDriver driver;     
@Test     public void FirstTest() {         
// declaration and instantiation of objects/variables     
System.setProperty("webdriver.chrome.driver","C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe"); 
driver = new ChromeDriver(); //comment the above 2 lines and uncomment below 2 lines to use Chrome //
System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe"); //
WebDriver driver = new ChromeDriver();              
String baseUrl = "https://www.lambdatest.com/";         
String expectedTitle = "LambdaTest - Perform all your tests on cloud";         
String actualTitle = "";           // launch Chrome and direct it to the Base URL         
driver.get(baseUrl);           // get the actual value of the title         
actualTitle = driver.getTitle();           /*          
* compare the actual title of the page with the expected one and print         
 * the result as "Passed" or "Failed"          */         

if (actualTitle.contentEquals(expectedTitle)){             
System.out.println("Test Passed!");         } else {             
System.out.println("Test Failed");         }               
 //close Fire fox         driver.close();           
 }   }


After writing the code, save it and right click on New Test.java → Run as→ TestNG Test.

Once you click on it, you’ll see a Chrome browser window opening the website that you’ve entered in your code to test. And it will automatically close as soon as the test is completed and in the output section below, you’ll see "Test Passed" as the status of your test on the console below.


With this, you have run your first automation test in TestNG using a local webdriver.

To verify the title of a given webpage matches the one already specified.

Executing Cross-Browser Automation Testing

So far, you have seen how to run a TestNG script using a local webdriver. That is all easy and quick, however, using a local webdriver for performing automation testing with Selenium will not provide you with a variety of browsers to test your website or web app on! You can only perform your testing on the browsers that are installed in your local machine. Considering the abundance of browsers on the internet, it could be nearly impossible to have your website test over every web browser through your local machine. This is where cloud testing plays a crucial part. LambdaTest is a cloud-based cross-browser testing tool which allows you to run your Selenium scripts using a remote webdriver. This remote webdriver would allow you to perform your test on over 2,000+ browsers and browser versions supported by LambdaTest Selenium grid. LambdaTest also allows you to perform a test on your locally hosted web apps or web pages through an SSH tunnel. This way you don’t need to install an excessive number of browsers on your OS for higher coverage of test results.

Executing A Single Instance In LambdaTest Using TestNG

A couple changes in your code is all that you would need for running your Selenium test script on LambdaTest Selenium grid. Here we will take a look at a different example to help demonstrate the LambdaTest Selenium grid.

We will be running a script of a simple to-do list app. In this list, our code will be marking two items as done, add a list item, and will display the total count of pending items. You can find the below code on our GitHub repository as well.

import org.openqa.selenium.By; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.Assert; 
import org.testng.annotations.AfterClass; 
import org.testng.annotations.BeforeClass; 
import org.testng.annotations.Test; 
import java.net.MalformedURLException; 
import java.net.URL; public class TestNGTodo{      
public String username = "YOUR_USERNAME";     
public String authkey = "YOUR_ACCESS_KEY";     
public static RemoteWebDriver driver = null;     
public String gridURL = "@beta.lambdatest.com/wd/hub";     
boolean status = false;        @BeforeClass     
public void setUp() throws Exception {        
DesiredCapabilities capabilities = new DesiredCapabilities();         
capabilities.setCapability("browserName", "chrome");         
capabilities.setCapability("version", "70.0");         
capabilities.setCapability("platform", "win10"); 
// If this cap isn't specified, it will just get the any available one         
capabilities.setCapability("build", "LambdaTestSampleApp");         
capabilities.setCapability("name", "LambdaTestJavaSample");         
capabilities.setCapability("network", true); // To enable network logs         
capabilities.setCapability("visual", true); // To enable step by step screenshot         
capabilities.setCapability("video", true); // To enable video recording         
capabilities.setCapability("console", true); // To capture console logs         try {             
driver = new RemoteWebDriver(new URL("https://" + username + ":" + authkey + gridURL), capabilities);         
} catch (MalformedURLException e) {             System.out.println("Invalid grid URL");         
} catch (Exception e) {             System.out.println(e.getMessage());         }     }        
@Test     public void testSimple() throws Exception {        try {               
//Change it to production page             driver.get("https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html");                            //Let's mark done first two items in the list.               
driver.findElement(By.name("li1")).click();             
driver.findElement(By.name("li2")).click();                           
// Let's add an item in the list.               
driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");             
driver.findElement(By.id("addbutton")).click();                            
// Let's check that the item we added is added in the list.             
String enteredText = driver.findElementByXPath("/html/body/div/div/div/ul/li[6]/span").getText();            
 if (enteredText.equals("Yey, Let's add it to list")) {                 status = true;             
}         } catch (Exception e) {             System.out.println(e.getMessage());         
}     }        @AfterClass     public void tearDown() throws Exception {        
if (driver != null) {             ((JavascriptExecutor) driver).executeScript("lambda-status=" + status);             driver.quit();         }     } }


If you look at the configurations selected for running the test, you'll see that they are our desired capabilities, and the code provided for those capabilities is from the LambdaTest Capabilities Generator.

LambdaTest Capabilities Generator


The button which says "Copy to clipboard" will help you to copy all the code based on your selections in just a single click.

That’s all you need for running your first automation test script using Selenium with TestNG at LambdaTest.

Executing Cross-Browser Parallel Testing

Now let us execute a single test on multiple configurations, known as parallel test execution.

In order to execute parallel testing, you must generate a testng.xml file along with a test case which would make use of these below parameters:

org.testng.annotations.Parameters

Here is an example of parallel testing.

import org.openqa.selenium.By; 
import org.openqa.selenium.Platform; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.remote.DesiredCapabilities; 
import org.openqa.selenium.remote.RemoteWebDriver; 
import org.testng.Assert; 
import org.testng.annotations.AfterClass; 
import org.testng.annotations.BeforeClass; 
import org.testng.annotations.Test; 
import java.net.MalformedURLException; 
import java.net.URL; public class TestNGTodo {      
public String username = "YOUR_USERNAME";     
public String authkey = "YOUR_ACCESS_KEY";     
public static RemoteWebDriver driver = null;    
 public String gridURL = "@beta.lambdatest.com/wd/hub";    
 boolean status = false;        @BeforeClass    
 @org.testng.annotations.Parameters(value={"browser","version","platform"})     
public void setUp() throws Exception {       
 DesiredCapabilities capabilities = new DesiredCapabilities();        
 capabilities.setCapability("browserName", "chrome");         
capabilities.setCapability("version", "70.0");        
 capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one         capabilities.setCapability("build", "LambdaTestSampleApp");        
 capabilities.setCapability("name", "LambdaTestJavaSample");        
 capabilities.setCapability("network", true); // To enable network logs         
capabilities.setCapability("visual", true); // To enable step by step screenshot       
  capabilities.setCapability("video", true); // To enable video recording         
capabilities.setCapability("console", true); // To capture console logs         
try {             driver = new RemoteWebDriver(new URL("https://" + username + ":" + authkey + gridURL), capabilities);         } catch (MalformedURLException e) {            
 System.out.println("Invalid grid URL");         
} catch (Exception e) {             
System.out.println(e.getMessage());         }     }       
 @Test     public void testSimple() throws Exception {       
 try {               //Change it to production page             
driver.get("https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html");                            
//Let's mark done first two items in the list.               
driver.findElement(By.name("li1")).click();             
driver.findElement(By.name("li2")).click();                          
 // Let's add an item in the list.               
driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");            
 driver.findElement(By.id("addbutton")).click();                           
 // Let's check that the item we added is added in the list.             
String enteredText = driver.findElementByXPath("/html/body/div/div/div/ul/li[6]/span").getText();            
 if (enteredText.equals("Yey, Let's add it to list")) {                 status = true;             }        
 } catch (Exception e) {             System.out.println(e.getMessage());         }     }      
  @AfterClass     public void tearDown() throws Exception {        if (driver != null) {            
 ((JavascriptExecutor) driver).executeScript("lambda-status=" + status);           
  driver.quit();         
}     } }


Now let us generate a tesng.xml file where we will be declaring basic test configurations such as the browser, browser version, and more.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="3" name="LambaTestSuite" parallel="tests">
 
  <test name="WIN8TEST">
  <parameter name="browser" value="firefox"/>
  <parameter name="version" value="62.0"/>
  <parameter name="platform" value="WIN8"/>
    <classes>
      <class name="lambdatest.TestNGTodo "/>
    </classes>
  </test> <!-- Test -->
 
  <test name="WIN10TEST">
  <parameter name="browser" value="chrome"/>
  <parameter name="version" value="70.0"/>
  <parameter name="platform" value="WIN10"/>
    <classes>
      <class name="lambdatest.TestNGTodo "/>
    </classes>
  </test> <!-- Test -->
  <test name="MACTEST">
  <parameter name="browser" value="safari"/>
  <parameter name="version" value="11.0"/>
  <parameter name="platform" value="macos 10.13"/>
    <classes>
      <class name="lambdatest.TestNGTodo"/>
    </classes>
  </test> <!-- Test -->
 
</suite>


That is all you need for successfully executing parallel automated tests using Selenium with TestNG on LambdaTest.

Nothing matches the feel you get after doing something new. So, feeling good after executing your first automation script? Let us know your experience in the comment section below.

Learn how enterprises are using tools to automate security in their DevOps toolchain with these DevSecOps Reference Architectures.

Topics:
automation testing ,testng ,testng automation framework ,devops ,selenium ,cross browser testing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}