Showing posts with label TestNg annotations. Show all posts
Showing posts with label TestNg annotations. Show all posts

Wednesday, October 5, 2016

Parameterization in TestNG and TestNG DataProviders

TestNG Parameters

There are times when we would like to run our tests against different data sets. Instead of hard coding the data set within tests itself, it will be more appropriate if we could pass our data as parameters to the test method. Thus the test logic remains same but the data on which the test is run changes and this is called data-driven testing.
One of the most important features of TestNG is its data-driven testing. It allows the user to pass parameter values to the test method as arguments, so the test ends up running for each data-set passed in.
TestNG supports two different ways of injecting parameter values.
  1. Parameterization through testng.xml
  2. DataProvider

In most cases, you'll come across a scenario where the business logic requires a hugely varying number of tests. Parameterized tests allow developers to run the same test over and over again using different values.

Passing Parameters with testng.xml 
With this technique, you define the simple parameters in the testng.xml file and then reference those parameters in the source files. Let us have an example to demonstrate how to use this technique to pass parameters.

I am going to create new TestNG class 'ParametrizationTest', Open Amazon site and try logging in by passing username and password as parameters.

Add the annotation @Parameters("myName") to this method. The parameter would be passed a value from testng.xml

package automationFramework;
import org.testng.annotations.Parameters;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ParametrizationTest {
    public static WebDriver sDriver = new SafariDriver();
  @Test
  @Parameters({"sUsername","sPassword"})
  public void testOne(String sUsername, String sPassword) throws InterruptedException {
      sDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      //Open website
      sDriver.get("http://amazon.com");
      //Verify Page title
      WebElement myAccountLink = sDriver.findElement(By.id("nav-link-yourAccount"));
     
      //Adding assertion check here. Test will only continue if below statement is True.
      Assert.assertTrue(myAccountLink.isDisplayed());
      //My Account Link will be clicked only if the above condition is true
      myAccountLink.click();
     
      Thread.sleep(1000);
      sDriver.findElement(By.xpath(".//*[@id='ap_email']")).sendKeys(sUsername);
      sDriver.findElement(By.xpath(".//*[@id='ap_password']")).sendKeys(sPassword);
      sDriver.findElement(By.xpath(".//*[@id='signInSubmit']")).click();
     
  }
}



Next, Pass the Parameters in testng.xml and run it. The output will look like this-


 


TestNG DataProviders

Passing Parameters with Dataproviders

When you need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc.), parameters can be passed using Data providers. A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the name is not supplied, the data provider’s name automatically defaults to the method’s name. A data provider returns an array of objects.
The following examples demonstrate how to use data providers.

 Let's start by creating a new TestNG class 'DataProviderTest'

1)  Define the method logons() which is defined as a Dataprovider using the annotation. This method returns array of object array.

2) Add a method test() to your DataProviderTest class. This method takes two strings as input parameters.

3) Add the annotation @Test(dataProvider = “LoginValidation”) to this method. The attribute dataProvider is mapped to “LoginValidation”.

package automationFramework;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderTest {
    public static WebDriver sDriver = new SafariDriver();
   
  @DataProvider(name= "LoginValidation")
  public static Object[][] credentials() {
 return new Object[][] { { "user1", "pass1" }, { "user2", "pass2" }};

}
  @Test(dataProvider="LoginValidation")
  public void testOne(String sUsername,String sPassword ) throws InterruptedException {
      sDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      //Open website
      sDriver.get("http://amazon.com");
      //Verify Page title
      WebElement myAccountLink = sDriver.findElement(By.id("nav-link-yourAccount"));
     
      //Adding assertion check here. Test will only continue if below statement is True.
      Assert.assertTrue(myAccountLink.isDisplayed());
      //My Account Link will be clicked only if the above condition is true
      myAccountLink.click();
     
      Thread.sleep(1000);
      sDriver.findElement(By.xpath(".//*[@id='ap_email']")).sendKeys(sUsername);
      sDriver.findElement(By.xpath(".//*[@id='ap_password']")).sendKeys(sPassword);
      sDriver.findElement(By.xpath(".//*[@id='signInSubmit']")).click(); 
  }
}

 
Run testng.xml file and see the Test Result. The output will look like this and it will show all the parameters - 




 

Tuesday, October 4, 2016

TestNG with WebDriver Introduction and setup

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use

Features of TestNG

  • Support for annotations
  • Support for parameterization
  • Advance execution methodology that do not require test suites to be created
  • Support for Data Driven Testing using Dataproviders
  • Enables user to set execution priorities for the test methods
  • Supports threat safe environment when executing multiple threads
  • Readily supports integration with various tools and plug-ins like build tools (Ant, Maven etc.), Integrated Development Environment (Eclipse).
  • Facilitates user with effective means of Report Generation using ReportNG.

TestNG is designed to cover all categories of tests:  unit, functional, end-to-end, integration, etc.

TestNG Plugin Installation in Eclipse
  1. Launch eclipse IDE -> Click on the Help option within the menu -> Select “Eclipse Marketplace” option within the dropdown.


  2. Enter the keyword “TestNG” in the search textbox and click on “Go” button as shown below. 
  3. Click on the “Go” button and click on the Install button to install TestNG.
  4. Click on “Confirm” button. Next, the application would prompt you to accept the license and then click on the “Finish” button.
  5. The installation is initiated now and the progress can be seen as following:
 Restart Eclipse. Next, Verify that TestNG appears in eclipse Preference. Click on Eclipse menu tab -> Preferences. TestNG should be visible in the Preference.




Annotations in TestNG

@BeforeSuite: The annotated method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeMethod: The annotated method will be run before each test method.
@AfterMethod: The annotated method will be run after each test method.
@Test: The annotated method is a part of a test case.

Now, Let's create first TestNG class. 


Right click on src and click on TestNG -> Create TestNG class


Fill out Package name and Class name along with select couple of annotations. In this example i am using @BeforeMethod and @AfterMethod and rewriting out FirstTestCase.





Let’s take an example of FirstTestCase and divide the test case in to three parts .
@BeforeMethod : Launch Safari and direct it to the Base URL
@Test : Find Page title and print console message
@AfterMethod : Close Safari browser

package automationFramework;

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

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterMethod;

public class TestNG {
    public WebDriver sDriver;
   
  @Test
  public void main() {
      String pageTitle = sDriver.getTitle().toString();
      System.out.println(pageTitle);
  }
  @BeforeMethod
  public void beforeMethod() {

      // Create a new instance of the Safari driver
      sDriver = new SafariDriver();
     
      //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
      sDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     
      String webSiteURL = "https://www.amazon.com/";
      //Launch the website
      sDriver.get(webSiteURL);
  }

  @AfterMethod
  public void afterMethod() {
      // Close the driver
      sDriver.close();
  }
}


Run the test by right click on the test case script and select Run As > TestNG Test.

TestNG produces reports in various formats.


  



Open project folder -> test-output and view index.html, emailable-report.html. Also view Default test.html inside Default suite folder.