You are on page 1of 14

Let s take an example of First Test Case and divide the test case in to three part

s .
@BeforeMethod : Launch Firefox and direct it to the Base URL
@Test : Enter Username & Password to Login, Print console message and Log out
@AfterMethod : Close Firefox browser
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
public class TestNG {
public WebDriver driver;
@Test
public void main() {
// Find the element that's ID attribute is 'account'(My Account)
driver.findElement(By.id("account")).click();
// Find the element that's ID attribute is 'log' (Username)
// Enter Username on the element found by above desc.
driver.findElement(By.id("log")).sendKeys("testuser_1");
// Find the element that's ID attribute is 'pwd' (Password)
// Enter Password on the element found by the above desc.
driver.findElement(By.id("pwd")).sendKeys("Test@123");
// Now submit the form. WebDriver will find the form for us from the eleme
nt
driver.findElement(By.id("login")).click();
// Print a Log In message to the screen
System.out.println(" Login Successfully, now it is the time to Log Off bud
dy.");

// Find the element that's ID attribute is 'account_logout' (Log Out)


driver.findElement(By.id("account_logout"));
}
@BeforeMethod
public void beforeMethod() {
// Create a new instance of the Firefox driver
driver = new FirefoxDriver();
//Put a Implicit wait, this means that any search for elements on the page
could take the time the implicit wait is set for before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch the Online Store Website
driver.get("http://www.onlinestore.toolsqa.wpengine.com");
}
@AfterMethod
public void afterMethod() {
// Close the driver
driver.quit();
}
}
-----------------------In testng.xml file we can specify multiple name (s) which needs to be executed.
In a project there may be many classes, but we want to execute only the selected
classes.
We can pass class names of multiple packages also. If say suppose, we want to ex
ecute two classes in one package and other class from some other package.

We need to specify the class names along with packages in between the classes ta
gs.
In the above xml, we have specified class name as com.first.example.demoOne and com
.first.example.demoOne which are in com.first.example package. And class name demoT
hree is in package com.second.example.
All the classes specified in the xml will get executes which have TestNG annotat
ions.

Below are the two example classes under


d.

com.first.example

package which is execute

Run as - Testsuite --

Package: com.first.example
Classname: demoOne
package com.first.example;
import org.testng.annotations.Test;
public class demoOne {
@Test
public void firstTestCase()
{
System.out.println("im in first test case from demoOne Class");
}
@Test
public void secondTestCase()
{
System.out.println("im in second test case from demoOne Class");
}
}
Classname: demoTwo
package com.first.example;
import org.testng.annotations.Test;
public class demoTwo {
@Test
public void firstTestCase()
{
System.out.println("im in first test case from demoTwo Class");
}
@Test
public void secondTestCase()
{
System.out.println("im in second test case from demoTwo Class");
}
}
Package: com.second.example
Classname: demoThree
package com.second.example;
import org.testng.annotations.Test;
public class demoThree {
@Test
public void firstTestCase()
{
System.out.println("im in first test case from demoThree Class")
;
}
@Test
public void secondTestCase()
{

System.out.println("im in second test case from demoThree Class"


);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<suite name="example suite 1" verbose="1" >
<test name="Regression suite 1" >
<classes>
<class name="com.first.example.demoOne"/>
<class name="com.first.example.demoTwo"/>
<class name="com.second.example.demoThree"/>
</classes>
</test>
</suite>
------------------------------DataProvider in TestNG
Marks a method as supplying data for a test method. The annotated method must re
turn an Object[][] where each Object[] can be assigned the parameter list of the
test method.
The @Test method that wants to receive data from this DataProvider needs to use
a dataProvider name equals to the name of this annotation.
The name of this data provider. If it's not supplied, the name of this data prov
ider will automatically be set to the name of the method.
In the below example we will pass the data from getData() method to data provide
r. We will send 3 rows and 2 columns ie. we will pass three different usernames
and passwords.
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProviderExample{
//This test method declares that its data should be supplied by the Data
Provider
// "getdata" is the function name which is passing the data
// Number of columns should match the number of input parameters
@Test(dataProvider="getData")
public void setData(String username, String password)
{
System.out.println("you have provided username as::"+username);
System.out.println("you have provided password as::"+password);
}
@DataProvider
public Object[][] getData()
{
//Rows - Number of times your test has to be repeated.
//Columns - Number of parameters in test data.
Object[][] data = new Object[3][2];
// 1st row

data[0][0] ="sampleuser1";
data[0][1] = "abcdef";
// 2nd row
data[1][0] ="testuser2";
data[1][1] = "zxcvb";
// 3rd row
data[2][0] ="guestuser3";
data[2][1] = "pass123";
return data;
}
}
----------------------package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.Parameters;
public class TestngParameters {
private static WebDriver driver;
@Test
@Parameters({ "sUsername", "sPassword" })
public void test(String sUsername, String sPassword) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.store.demoqa.com");
driver.findElement(By.xpath(".//*[@id='account']/a")).click();
driver.findElement(By.id("log")).sendKeys(sUsername);
driver.findElement(By.id("pwd")).sendKeys(sPassword);
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();
driver.quit();
}

}
<suite name="Suite">
<test name="ToolsQA">
<parameter name="sUsername" value="testuser_1"/>
<parameter name="sPassword" value="Test@123"/>
<classes>
<class name="automationFramework.TestngParameters" />
</classes>
</test>
</suite>
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProviderTest {
private static WebDriver driver;
@DataProvider(name = "Authentication")
public static Object[][] credentials() {
return new Object[][] { { "testuser_1", "Test@123" }, { "testuser_1", "T
est@123" }};
}
// Here we are calling the Data Provider object with its Name
@Test(dataProvider = "Authentication")
public void test(String sUsername, String sPassword) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.store.demoqa.com");

driver.findElement(By.xpath(".//*[@id='account']/a")).click();
driver.findElement(By.id("log")).sendKeys(sUsername);
driver.findElement(By.id("pwd")).sendKeys(sPassword);
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();
driver.quit();
}
}
---------------TestNG allows us to perform sophisticated groupings of test methods.
Using TestNG we can execute only set of groups while excluding another set. This
gives us the maximum flexibility in divide tests and doesn't require us to reco
mpile anything if you want to run two different sets of tests back to back.
Groups are specified in testng.xml file and can be used either under the or tag.
Groups specified in the tag apply to all the tags underneath.
package com.example.group;
import org.testng.annotations.Test;
public class groupExamples {
@Test(groups="Regression")
public void testCaseOne()
{
System.out.println("Im in testCaseOne - And in Regression Group");
}
@Test(groups="Regression")
public void testCaseTwo(){
System.out.println("Im in testCaseTwo - And in Regression Group");
}
@Test(groups="Smoke Test")
public void testCaseThree(){
System.out.println("Im in testCaseThree - And in Smoke Test Group");
}
@Test(groups="Regression")
public void testCaseFour(){
System.out.println("Im in testCaseFour - And in Regression Group");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Sample Suite">
<test name="testing">
<groups>
<run>
<include name="Regression"/>
</run>
</groups>
<classes>
<class name="com.example.group.groupExamples" />

</classes>
</test>
</suite>
----------------------------TestNG with Ant
We will create a sample project and execute TestNG tests using ANT build.xml. Be
fore creating build.xml file, we will first create a project with some sample te
stng tests.
Before proceeding, please make sure you have installed ANT in your machine.
In Build.xml we will mainly see the below tags
1. project - Project is the staring point of the Ant configuration file and cons
ists of the entire configuration with respect to building a project
2. target - A target is a set of tasks that that you want to execute during the
build process.
3. task - Task is a piece of code that can be executed
4. property - Property tags are an important way to customize a build process or
to provides way to define shortcuts to reuse repeatedly inside a build file
You can find more details of build file in Apache Ant manual
Step 1: Create a project
Step 2: Create sample packages as 'com.pack.one' and 'com.pack.two'
Step 3: Create multiple classes with in packages 'TestA' under 'com.pack.one' an
d 'TestB' under 'com.pack.two'
package com.pack.one;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestA {
@BeforeClass
public void setUp() {
System.out.println("*** In class - Test A ***");
}
@Test
public void testOne() {
System.out.println("hello");
}
@Test
public void testTwo() {
System.out.println("hello");
}
@AfterClass
public void tearDown() {
System.out.println("*** End of class***");
}

}
Create class 'TestB' under 'com.pack.two'
package com.pack.two;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestB {
@BeforeClass
public void setUp() {
System.out.println("*** In class - Test B ***");
}
@Test
public void testOne() {
System.out.println("hello");
}
@Test
public void testTwo() {
System.out.println("hello");
}
@AfterClass
public void tearDown() {
System.out.println("*** End of class***");
}
}
Step 4: Create testng.xml file and add the classes to test
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Sample Test Suite">
<test name="Sample Test">
<classes>
<class name="com.pack.one.TestA"/>
<class name="com.pack.two.TestB"/>
</classes>
</test>
</suite>
To create build.xml file, Right click on the project -> New -> File -> Enter the
file name and Click on Finish button.
And the below is the build.xml file.
<project name="Sample Ant build" basedir=".">
<!-- ========== Initialize Properties ==================================
= -->
<!-- set global properties for build -->
<property name="basedir" value="." />
<property name="lib" value="${basedir}/lib" />
<property name="src" value="${basedir}/src" />
<property name="bin" value="${basedir}/bin" />
<property name="report-dir" value="${basedir}/Test-Report" />
<property name="testng-report-dir" value="${report-dir}/TestNGreport" />
<!-- ====== Set the classpath ==== -->

<path id="classpath">
<pathelement location="${bin}" />
<fileset dir="${lib}">
<include name="*.jar" />
</fileset>
</path>
<!-- Delete directories -->
<target name="delete-dir">
<delete dir="${bin}" />
<delete dir="${report-dir}" />
</target>
<!-- Creating directories -->
<target name="create" depends="delete-dir">
<mkdir dir="${bin}" />
<mkdir dir="${report-dir}" />
</target>
<!-- Compile the java code from ${src} into ${bin} -->
<target name="compile" depends="create">
<javac srcdir="${src}" classpathref="classpath" includeAntRuntim
e="No" destdir="${bin}" />
<echo> /* Compiled Directory Classes */ </echo>
</target>
<!-- Runs the file and generates Reportng report for TestNG-->
<taskdef name="testng" classname="org.testng.TestNGAntTask" classpathref
="classpath" />
<target name="testng-execution" depends="compile">
<mkdir dir="${testng-report-dir}" />
<testng outputdir="${testng-report-dir}" classpathref="classpath
" useDefaultListeners="true">
<xmlfileset dir="${basedir}" includes="testng.xml" />
</testng>
</target>
</project>
-------------Parameterization in TestNG using testng.xml
TestNG allows the user to pass values to test methods as arguments by using para
meter annotations through testng.xml file.
Some times it may be required for us to pass values to test methods during run t
ime. Like we can pass user name and password through testng.xml instead of hard
coding it in testmethods. or we can pass browser name as parameter to execute in
specific browser.
Let us now try to understand parameterization with a basic example.
package com.parameterization;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestParameters {

@Parameters({ "browser" })
@Test
public void testCaseOne(String browser) {
System.out.println("browser passed as :- " + browser);
}
@Parameters({ "username", "password" })
@Test
public void testCaseTwo(String username, String password) {
System.out.println("Parameter for User Name passed as :- " + use
rname);
System.out.println("Parameter for Password passed as :- " + pass
word);
}
}
In the above class, for Test Method 'testCaseOne', we are passing two parameters
'username' and 'password' as input to test method.
The below is the testng.xml file, in which we need to pass the parameter values
for the test method
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Parameterization Test Suite">
<test name="Testing Parameterization">
<parameter name="browser" value="Firefox"/>
<parameter name="username" value="testuser"/>
<parameter name="password" value="testpassword"/>
<classes>
<class name="com.parameterization.TestParameters" />
</classes>
</test>
</suite>
In the above testng.xml file, we have two attributes for parameter tag, the name
attribute which defines name of
the parameter, and the value attribute defines the value of the parameter.

------------------------

Passing data to DataProvider from Excel sheet


In this example we will see how to pass the data to Dataproviders by reading the
data from excel sheet. DataProvider helps to send multiple sets of data to a te
st method. But here we need to make sure that the array returned by the dataprov
ider should match with the test method parameters.
We will write a simple program in which we will validate login screen by taking
multiple usernames and passwords. The annotated method must return object[][] wh
ere each object[] can be assigned to the test method one as username and the oth
er parameter as password.
Step 1: First create a method to read excel data and return string array.
Step 2: Create before class and after class methods which helps in getting the b
rowser and closing them when done.
Step 3: Create a data provider which actually gets the values by reading the exc
el.

Step 4: Create a Test which takes two parameters username and password.
Step 5: Add dataprovider name for @Test method to receive data from dataprovider
.
package com.pack;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import
import
import
import
import
import
import
import
import

org.testng.Assert;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.WebDriverWait;
org.testng.annotations.BeforeClass;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ReadExcelDataProvider {
public WebDriver driver;
public WebDriverWait wait;
String appURL = "https://www.linkedin.com/";
//Locators
private By
private By
private By
private By

byEmail = By.id("session_key-login");
byPassword = By.id("session_password-login");
bySubmit = By.id("signin");
byError = By.id("global-alert-queue");

@BeforeClass
public void testSetup() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
@Test(dataProvider="empLogin")
public void VerifyInvalidLogin(String userName, String password) {
driver.navigate().to(appURL);
driver.findElement(byEmail).sendKeys(userName);
driver.findElement(byPassword).sendKeys(password);
//wait for element to be visible and perform click
wait.until(ExpectedConditions.visibilityOfElementLocated(bySubmi
t));
driver.findElement(bySubmit).click();
//Check for error message
wait.until(ExpectedConditions.presenceOfElementLocated(byError))
;
String actualErrorDisplayed = driver.findElement(byError).getTex
t();
String requiredErrorMessage = "Please correct the marked field(s

) below.";
Assert.assertEquals(requiredErrorMessage, actualErrorDisplayed);
}
@DataProvider(name="empLogin")
public Object[][] loginData() {
Object[][] arrayObject = getExcelData("D:/sampledoc.xls","Sheet1
");
return arrayObject;
}
/**
* @param File Name
* @param Sheet Name
* @return
*/
public String[][] getExcelData(String fileName, String sheetName) {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet(sheetName);
int totalNoOfCols = sh.getColumns();
int totalNoOfRows = sh.getRows();
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCo
ls];
for (int i= 1 ; i < totalNoOfRows; i++) {
for (int j=0; j < totalNoOfCols; j++) {
arrayExcelData[i-1][j] = sh.getCell(j, i
).getContents();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
@Test
public void tearDown() {
driver.quit();
}
}

How to run TestNG using ANT

First Open the command and navigate to the respective project path in the system
. Under that folder, we need to enter the below command
ant testng-execution
Now it will show you the build.xml file that is getting executed and then it wil
l compile and execute the TestNG tests. The below is the screen shot that you sh
ould observe.
--------------

You might also like