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;
public void main() {
// Find the element that's ID attribute is 'account'(My Account)
// Find the element that's ID attribute is 'log' (Username)
// Enter Username on the element found by above desc.
// Find the element that's ID attribute is 'pwd' (Password)
// Enter Password on the element found by the above desc.
// Now submit the form. WebDriver will find the form for us from the eleme
// Print a Log In message to the screen
System.out.println(" Login Successfully, now it is the time to Log Off bud

//Put a Implicit wait.timeouts().// Find the element that's ID attribute is 'account_logout' (Log Out) driver. We can pass class names of multiple packages also. If say suppose.quit(). .second. In a project there may be many classes.toolsqa. And class name demoT hree is in package com.findElement(By. this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception driver. We need to specify the class names along with packages in between the classes ta gs. TimeUnit. we have specified class name as com. we want to ex ecute two classes in one package and other class from some other package.first.id("account_logout")).com").xml file we can specify multiple name (s) which needs to be executed.example package.demoOne which are in com. but we want to execute only the selected classes.example. In the above xml.SECONDS).demoOne and com . All the classes specified in the xml will get executes which have TestNG annotat ions.first.wpengine. } } -----------------------In testng.example. } @BeforeMethod public void beforeMethod() { // Create a new instance of the Firefox driver driver = new FirefoxDriver().onlinestore.implicitlyWait(10.first.example.manage().get("http://www. //Launch the Online Store Website driver. } @AfterMethod public void afterMethod() { // Close the driver driver.

public class demoOne { @Test public void firstTestCase() { System.Test.testng. } @Test public void secondTestCase() { . } @Test public void secondTestCase() { System.example.Testsuite -- Package: com. public class demoThree { @Test public void firstTestCase() { System.first.example package which is execute Run as .out.out.first.example Classname: demoThree package com.println("im in second test case from demoOne Class").second.example Classname: demoOne package com.example. import org.testng.println("im in first test case from demoThree Class") . } @Test public void secondTestCase() { System.println("im in first test case from demoOne Class").first. import org.Test.out.annotations.out.first. public class demoTwo { @Test public void firstTestCase() { System.Below are the two example classes under d.testng. import org. } } Package: com. } } Classname: demoTwo package com. com.println("im in first test case from demoTwo Class").annotations.Test.out.example.annotations.second.println("im in second test case from demoTwo Class").

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

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

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

driver.And in Regression Group").quit(). import org.annotations.out. 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.findElement(By.id("pwd")).//*[@id='account_logout']/a")).click().And in Regression Group").sendKeys(sPassword).id("login")).click().xpath(". driver.And in Smoke Test Group").driver. } } <?xml version="1.groupExamples" /> . } @Test(groups="Regression") public void testCaseTwo(){ System.0" encoding="UTF-8"?> <suite name="Sample Suite"> <test name="testing"> <groups> <run> <include name="Regression"/> </run> </groups> <classes> <class name="com. Groups are specified in testng.out. driver.out.group.testng. } @Test(groups="Regression") public void testCaseFour(){ System.println("Im in testCaseThree .xpath(". } @Test(groups="Smoke Test") public void testCaseThree(){ System.findElement(By. } } ---------------TestNG allows us to perform sophisticated groupings of test methods.click().findElement(By.example. driver.out. Groups specified in the tag apply to all the tags underneath.println("Im in testCaseOne .id("log")).group. package com.println("Im in testCaseFour .sendKeys(sUsername).And in Regression Group"). public class groupExamples { @Test(groups="Regression") public void testCaseOne() { System.xml file and can be used either under the or tag.Test.example.//*[@id='account']/a")).findElement(By.findElement(By. driver.println("Im in testCaseTwo .

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

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

Test. Like we can pass user name and password through testng. public class TestParameters { .Runs the file and generates Reportng report for TestNG--> <taskdef name="testng" classname="org. import org.xml TestNG allows the user to pass values to test methods as arguments by using para meter annotations through testng.testng. Let us now try to understand parameterization with a basic example.xml instead of hard coding it in testmethods.parameterization. or we can pass browser name as parameter to execute in specific browser. Some times it may be required for us to pass values to test methods during run t ime.annotations.Parameters.jar" /> </fileset> </path> <!-.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.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> <!-.xml" /> </testng> </target> </project> -------------Parameterization in TestNG using testng. import org.testng. package com.<path id="classpath"> <pathelement location="${bin}" /> <fileset dir="${lib}"> <include name="*.annotations.xml file.testng.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> <!-.

" + use rname)." + pass word). Step 1: First create a method to read excel data and return string array.println("browser passed as :.@Parameters({ "browser" }) @Test public void testCaseOne(String browser) { System. } } In the above class. ------------------------ 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.out. DataProvider helps to send multiple sets of data to a te st method. Step 3: Create a data provider which actually gets the values by reading the exc el.println("Parameter for User Name passed as :. and the value attribute defines the value of the parameter." + browser).xml file. } @Parameters({ "username".0. We will write a simple program in which we will validate login screen by taking multiple usernames and passwords. System. . the name attribute which defines name of the parameter. The below is the testng. String password) { System. for Test Method 'testCaseOne'.xml file.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.out. we have two attributes for parameter tag. we are passing two parameters 'username' and 'password' as input to test method.org/testng-1.out.TestParameters" /> </classes> </test> </suite> In the above testng. Step 2: Create before class and after class methods which helps in getting the b rowser and closing them when done. 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. But here we need to make sure that the array returned by the dataprov ider should match with the test method parameters. in which we need to pass the parameter values for the test method <!DOCTYPE suite SYSTEM "http://testng.println("Parameter for Password passed as :. "password" }) @Test public void testCaseTwo(String username.parameterization.

String requiredErrorMessage = "Please correct the marked field(s .read.ui. driver.id("signin"). public WebDriverWait wait.FirefoxDriver.window().testng.until(ExpectedConditions.openqa.until(ExpectedConditions.io. import java.openqa.selenium.id("session_password-login").openqa.testng. String actualErrorDisplayed = driver.to(appURL). org.ui.annotations.getTex t(). bySubmit = By.io.selenium.Assert. byPassword = By. driver.findElement(byEmail). //Check for error message wait.FileNotFoundException.sendKeys(password).Sheet. package com. driver. public class ReadExcelDataProvider { public WebDriver driver.annotations.testng. byError = By.FileInputStream.findElement(byPassword).navigate(). wait = new WebDriverWait(driver. driver. import java. 5).selenium.IOException.click().presenceOfElementLocated(byError)) .WebDriverWait.findElement(byError). @BeforeClass public void testSetup() { driver=new FirefoxDriver().openqa.pack.Test.BeforeClass. String password) { driver.biff.findElement(bySubmit).Step 4: Create a Test which takes two parameters username and password. org.sendKeys(userName).openqa. org. import jxl. import jxl.Workbook.maximize().id("global-alert-queue"). org.BiffException.selenium. org.WebDriver. org.io. //Locators private By private By private By private By byEmail = By.visibilityOfElementLocated(bySubmi t)). org.DataProvider. org. import java.annotations.linkedin. Step 5: Add dataprovider name for @Test method to receive data from dataprovider .id("session_key-login").testng.support.manage().selenium. import jxl. import import import import import import import import import org.ExpectedConditions.By.firefox. } @Test(dataProvider="empLogin") public void VerifyInvalidLogin(String userName. String appURL = "https://www.support.com/". //wait for element to be visible and perform click wait.

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

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. Under that folder. The below is the screen shot that you sh ould observe. -------------- .First Open the command and navigate to the respective project path in the system .