White Box Testing
Test your code
   Home      TestNG Data Driven Testing with Data Provider
 
TestNG Data Driven Testing with DataProvider

DataProvider allows numbers of test data on same test case and remove limitation of simple parameters through testing.xml. With the help of DataProvider we can pass complex parameters or Java objects to a test method

@DataProvider marks a method as supplying data for a test method and should be always return “Object[][]” or “Iterator<Object[]>”, Iterator allows you to create your test data lazily. The name attribute of @DataProvider gives a significant name for parameter list to be used. With the parallel attribute of @DataProvider test can be run in parallel

To call a test with number of parameters from a data provider, use dataProvider=”data-provider-name” attribute of @Test

import org.testng.annotations.*;

import org.testng.Assert;

import SampleTest.Source.Calculator;

 

public class CalculatorTestAdd {

   @DataProvider(name = "data-provider", parallel = true)

   public Object[][] data() {

      return new Object[][] { { 0, 5, 5 }, { 1, 5, 6 }, { 100, 5, 105 }};

   }

   @Test(dataProvider="data-provider")

   public final void testAdd(int op1, int op2, int expResult) {

      Calculator cal = new Calculator();

      Assert.assertEquals(cal.add(op1,op2), expResult, "actual not matching with expected");

   }

}


DataProvider can be in separate class, in that case mention dataProviderClassin calling method

public class CalculatorTest{

   @DataProvider(name = "data-provider")

   public Object[][] data() {

      return new Object[][] { { 0, 5, 5 }, { 1, 5, 6 }, { 100, 5, 105 }};

   }

}

public class CalculatorTestAdd{

   @Test(dataProvider="data-provider", dataProviderClass= CalculatorTest.class)

   public final void testAdd(int op1, int op2, int expResult) {

      Calculator cal = new Calculator();

      Assert.assertEquals("actual not matching with expected", cal.add(op1,op2),expResult);

   }

}
 
 
Sample Source Code
 

 
External References