Part 2: Scripting using TestNG…

Now that we learned the workflow in a TestNG script, let’s update our ‘FirstTestNScript’ script to include two test cases that we mentioned in our last post.

First Test Case:Navigate to New Tours application and perform successful login.
Second Test Case:Navigate to New Tours application and perform successful registration. Click ‘Register’ link to go Register Page. Enter first name, last name, username, password, confirm password and click Submit to complete registration process.

This is how our test website looks like:

Test website
    1. First step is to create some test data for our first test case. It will require an username and password as test data. To accommodate this, we will update the ‘@DataProvider‘ method with a new name and we will also use two sets of test data (even though it’s same data). This will allow our test to execute twice with different set of data. Below is the code for the ‘@DataProvider‘ method.
      	//DataProvider method for login data
      	@DataProvider
      	public Object[][] loginDP() {
      		//username = demo, passowrd = demo
      		return new Object[][] {{"demo", "demo"}, {"demo", "demo"}};
      	}
      
    2. Every selenium script starts with a driver initialization. We will initialize the WebDriver inside our class but outside of all methods.

      Initialize WebDriver inside the Class
    3. Next step is to set the system properties. System properties setting needs to be done before assigning the WebDriver to a browser driver. In our test, we will set the system properties inside ‘@BeforeTest‘ method as we are not changing the browser type. However you can set the property inside ‘@Test‘ method also. Below is the code for ‘@BeforeTest‘.
      	//Setting System Properties
      	@BeforeTest
      	public void beforeTest() {
      		System.out.println("This is Before Test");
      		// Setting System properties
      		System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/Chrome/chromedriver");
      	}
      
    4. After setting the property, next step is to assign the WebDriver to a browser driver. Since we are planning to use the same browser type for both of our tests, we will do the browser assigning part in ‘@BeforeMethod‘. Note that ‘@Before/AfterMethod‘ always execute before and after of every ‘@Test‘ method. Below is the code for ‘@BeforeMethod‘.
      	//Assign WebDriver
      	@BeforeMethod
      	public void beforeMethod() {
      		System.out.println("This is Before Method");
      		// Assign WebDriver to ChromeDriver
      		driver = new ChromeDriver();
      		//Maximize window
      		driver.manage().window().maximize();
      		//Navigate to New Tours URL
      		driver.get("http://newtours.demoaut.com");
      	}
      
    5. Let’s create our first test case. We will use ‘@Test‘ method for our logic. For better understanding, we will update our ‘@Test‘ method with a new name and we will also use the new Data Provider. The ‘@Test‘ method will have new set of parameters. By default TestNG provides Integer type and String type parameters. Since our Data Provider has only String types, we will update the same in ‘@Test‘ method also.
      	@Test(dataProvider = "loginDP")
      	public void firstTestCase(String username, String password) {
      		System.out.println("This is our First Test Method");
      		//Enter username as demo
      		driver.findElement(By.name("userName")).sendKeys(username);
      
      		//Enter password as demo
      		driver.findElement(By.name("password")).sendKeys(password);
      
      		//Click Sign in button
      		driver.findElement(By.name("login")).click();
      
      		//Assert if Sign Off is displayed after logging in
      		Assert.assertTrue(driver.findElement(By.linkText("SIGN-OFF")).isDisplayed());
                      System.out.println("First Test Case Passed");	  
      	}
      
    6. Once the test is completed, next step is to close the driver. As mentioned, ‘@AfterMethod‘ comes after the ‘@Test‘ method, so the best way is to update the ‘@AfterMethod‘ with the closing codes. Below is the code for ‘@AfterMethod‘ method.
      	@AfterMethod
      	public void afterMethod() {
      		System.out.println("This is After Method");
      		// Close and quit the driver to close the Browser
      		  driver.close();
      		  driver.quit();
      	}
      
    7. Now that we completed our first test case, let’s execute the script by doing a right click on ‘FirstTestNScript’ and click Run As -> 2.TestNG Test.
    8. As we complete our execution we will see following messages in the console.

      First Test Case Passed
    9. Now that our first test case is completed, let’s focus on our second test case. Second Test Case requires a different data set up. For that we will create a new Data Provider. Below is the code for a new ‘@DataProvider‘ method. We will name it as ‘registerDP’. Notice that we used only one set of data. This means the second test case will execute only once.
      	//DataProvider method for registering
      	  @DataProvider
      	  public Object[][] registerDP() {
      		/*first name = fname, last name = lname, username = user, password = pwd, confirm password = pwd */
      	    return new Object[][] {{ "fname","lname","user","pwd","pwd"}};
      	  }
      
    10. To create a new test case, we will have to create a new ‘@Test‘ method. As mentioned, the logic of a test case is always written in ‘@Test‘ method. Below is the code for a new ‘@Test‘ method. Notice that it has a name “secondTestCase” and it uses a new Data Provider “registerDP”. The parameters are also updated.
      	@Test(dataProvider = "registerDP")
      	public void secondTestCase(String fname, String lname, String username, String pwd, String cpwd){
      		  System.out.println("This is Second Test Method");
      		  //Click Register link in Home page
      		  driver.findElement(By.linkText("REGISTER")).click();
      		  //Enter first name as fname
      		  driver.findElement(By.name("firstName")).sendKeys(fname);
      		  //Enter last name as lname
      		  driver.findElement(By.name("lastName")).sendKeys(lname);
      		  //Enter username as user
      		  driver.findElement(By.name("email")).sendKeys(username);
      		  //Enter password as pwd
      		  driver.findElement(By.name("password")).sendKeys(pwd);
      		  //Enter confirm password as cpwd
      		  driver.findElement(By.name("confirmPassword")).sendKeys(cpwd);
      		  //Click Submit to complete registration process
      		  driver.findElement(By.name("register")).click();
      		  System.out.println("Second Test Case Passed");	
      	}
      
    11. Now that our second ‘@Test‘ method is also complete, we can run our ‘FirstTestNScript’ script to execute both of our test cases. Notice that for second test case we don’t have to update ‘@Before/AfterMethod‘ as the same methods will be executed for both ‘@Test‘ methods. Below is the test results after execution is complete. Notice that first test case runs twice and second test case runs only once. This is because the Data Providers are defined in that manner.

      Test Results
    12. If we refresh the ‘test-output‘ folder, there will be many HTML reports. We can view them by doing a right click and Open With -> Web Browser.
    13. Complete code for this project is provided below. Unused annotations can be removed.
      package com.selenium.testcase;
      
      import org.testng.annotations.Test;
      import org.testng.annotations.BeforeMethod;
      import org.testng.annotations.AfterMethod;
      import org.testng.annotations.DataProvider;
      import org.testng.annotations.BeforeClass;
      import org.openqa.selenium.By;
      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.chrome.ChromeDriver;
      import org.testng.Assert;
      import org.testng.annotations.AfterClass;
      import org.testng.annotations.BeforeTest;
      import org.testng.annotations.AfterTest;
      import org.testng.annotations.BeforeSuite;
      import org.testng.annotations.AfterSuite;
      
      public class FirstTestNScript {
      
      	WebDriver driver;
      
      	@Test(dataProvider = "loginDP")
      	public void firstTestCase(String username, String password) {
      		System.out.println("This is our First Test Method");
      		// Enter username as demo
      		driver.findElement(By.name("userName")).sendKeys(username);
      		// Enter password as demo
      		driver.findElement(By.name("password")).sendKeys(password);
      		// Click Sign in button
      		driver.findElement(By.name("login")).click();
      		// Assert if Sign Off is displayed after logging in
      		Assert.assertTrue(driver.findElement(By.linkText("SIGN-OFF")).isDisplayed());
      		System.out.println("First Test Case Passed");
      	}
      
      	@Test(dataProvider = "registerDP")
      	public void secondTestCase(String fname, String lname, String username, String pwd, String cpwd) {
      		System.out.println("This is Second Test Method");
      		// Click Register link in Home page
      		driver.findElement(By.linkText("REGISTER")).click();
      		// Enter first name as fname
      		driver.findElement(By.name("firstName")).sendKeys(fname);
      		// Enter last name as lname
      		driver.findElement(By.name("lastName")).sendKeys(lname);
      		// Enter username as user
      		driver.findElement(By.name("email")).sendKeys(username);
      		// Enter password as pwd
      		driver.findElement(By.name("password")).sendKeys(pwd);
      		// Enter confirm password as cpwd
      		driver.findElement(By.name("confirmPassword")).sendKeys(cpwd);
      		// Click Submit to complete registration process
      		driver.findElement(By.name("register")).click();
      		System.out.println("Second Test Case Passed");
      	}
      
      	// Assign WebDriver
      	@BeforeMethod
      	public void beforeMethod() {
      		System.out.println("This is Before Method");
      		// Assign WebDriver to ChromeDriver
      		driver = new ChromeDriver();
      		// Maximize window
      		driver.manage().window().maximize();
      		// Navigate to New Tours URL
      		driver.get("http://newtours.demoaut.com");
      	}
      
      	@AfterMethod
      	public void afterMethod() {
      		System.out.println("This is After Method");
      		// Close and quit the driver to close the Browser
      		driver.close();
      		driver.quit();
      	}
      
      	// DataProvider method for login data
      	@DataProvider
      	public Object[][] loginDP() {
      		// username = demo, passowrd = demo
      		return new Object[][] { { "demo", "demo" }, { "demo", "demo" } };
      	}
      
      	// DataProvider method for registering
      	@DataProvider
      	public Object[][] registerDP() {
      		// first name = fname, last name = lname, username = user, password =
      		// pwd, confirm password = pwd
      		return new Object[][] { { "fname", "lname", "user", "pwd", "pwd" } };
      	}
      
      	@BeforeClass
      	public void beforeClass() {
      		System.out.println("This is Before Class");
      	}
      
      	@AfterClass
      	public void afterClass() {
      		System.out.println("This is After Class");
      	}
      
      	// Setting System Properties
      	@BeforeTest
      	public void beforeTest() {
      		System.out.println("This is Before Test");
      		// Setting System properties
      		System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/Chrome/chromedriver");
      	}
      
      	@AfterTest
      	public void afterTest() {
      		System.out.println("This is After Test");
      	}
      
      	@BeforeSuite
      	public void beforeSuite() {
      		System.out.println("This is Before Suite");
      	}
      
      	@AfterSuite
      	public void afterSuite() {
      		System.out.println("This is After Suite");
      	}
      }
      

With this we came to end on TestNG scripting. In the next post we will focus on configuring our test case with the help of testing.xml. Please share your comments. Happy Learning!

Additional Information:

There are many ways to configure the ‘@Test‘ method. Like for instance we can decide on which order the tests need to be executed, similarly we can group our tests in the way we want. For example in our above ‘FirstTestNScript’ script, if we want to execute the second test case first and then execute the first test case, we can easily configure this by setting the priority inside ‘@Test‘ annotation. Below will be code if we are setting the priority.

	@Test(dataProvider = "loginDP", priority=2)
	public void firstTestCase(String username, String password) {
		System.out.println("This is our First Test Method");
		// Enter username as demo
		driver.findElement(By.name("userName")).sendKeys(username);
		// Enter password as demo
		driver.findElement(By.name("password")).sendKeys(password);
		// Click Sign in button
		driver.findElement(By.name("login")).click();
		// Assert if Sign Off is displayed after logging in
		Assert.assertTrue(driver.findElement(By.linkText("SIGN-OFF")).isDisplayed());
		System.out.println("First Test Case Passed");
	}

	@Test(dataProvider = "registerDP", priority=1)
	public void secondTestCase(String fname, String lname, String username, String pwd, String cpwd) {
		System.out.println("This is Second Test Method");
		// Click Register link in Home page
		driver.findElement(By.linkText("REGISTER")).click();
		// Enter first name as fname
		driver.findElement(By.name("firstName")).sendKeys(fname);
		// Enter last name as lname
		driver.findElement(By.name("lastName")).sendKeys(lname);
		// Enter username as user
		driver.findElement(By.name("email")).sendKeys(username);
		// Enter password as pwd
		driver.findElement(By.name("password")).sendKeys(pwd);
		// Enter confirm password as cpwd
		driver.findElement(By.name("confirmPassword")).sendKeys(cpwd);
		// Click Submit to complete registration process
		driver.findElement(By.name("register")).click();
		System.out.println("Second Test Case Passed");
	}

Similarly there are many other ways by which we can configure the ‘@Test‘ method. Visit the below link for more information:

TestNG Annotations