Showing posts with label macOS Sierra. Show all posts
Showing posts with label macOS Sierra. 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 - 




 

TestNG Asserts example and explanation

Assertions in TestNG

Asserts helps us to verify the conditions of the test and decide whether test has failed or passed. A test is considered successful ONLY if it is completed without throwing any exception.

There will be many situations in the test where you just like to check the presence of an element. All you need to do is to put an assert statement on to it to verify its existence.

Here we are verifying if the page title is equal to 'Google' or not. If the page title is not matching with the text / title that we provided, it will fail the test case.

Different Asserts Statements
1) Assert.assertTrue() & Assert.assertFalse()

To explain you what is assertion, lets us look into below code sample.
I am going to create new TestNG class 'AssertTest'.

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.Test;

public class AssertTest {
    public static WebDriver sDriver = new SafariDriver();
   
  @Test
  public void testOne() 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);
  }
}


Let's run the code and verify the output.

 Assert.assertFalse() works opposite of Assert.assertTrue(). It means that if you want your test to continue only if when some certain element is not present on the page. You will use Assert false, so it will fail the test in case of the element present on the page.


Like wise there are many Assertions provided by the TestNG. The below are the few which are used commonly.
assertEqual(String actual,String expected) :- It takes two string arguments and checks whether both are equal, if not it will fail the test.

assertEqual(String actual,String expected, String message) :- It takes three string arguments and checks whether both are equal, if not it will fail the test and throws the message which we provide.
assertEquals(boolean actual,boolean expected) :- It takes two boolean arguments and checks whether both are equal, if not it will fail the test.

assertEquals(java.util.Collection actual, java.util.Collection expected, java.lang.String message) :- Takes two collection objects and verifies both collections contain the same elements and with the same order. if not it will fail the test with the given message.

Assert.assertTrue(condition) :- It takes one boolean arguments and checks that a condition is true, If it isn't, an AssertionError is thrown.

Assert.assertTrue(condition, message) :- It takes one boolean argument and String message. It Asserts that a condition is true. If it isn't, an AssertionError, with the given message, is thrown.

Assert.assertFalse(condition) :- It takes one boolean arguments and checks that a condition is false, If it isn't, an AssertionError is thrown.

Assert.assertFalse(condition, message) :- It takes one boolean argument and String message. It Asserts that a condition is false. If it isn't, an AssertionError, with the given message, is thrown.