DataProvider With method


If you declare your @DataProvider as taking a java.lang.reflect.Method as first parameter, TestNG will pass the current test method for this first parameter. This is particularly useful when several test methods use the same @DataProvider and you want it to return different values depending on which test method it is supplying data for.

Lets create java class

package testngexp;
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

publicclass dpmethodexp {
@Test(dataProvider="dpmethod")
publicvoid logintestEnv(String username, String pwd) {
System.out.println("UserName-->"+username);
System.out.println("Password-->"+pwd);
}
@Test(dataProvider="dpmethod")
publicvoid loginProductionEnv(String username, String pwd) {
System.out.println("UserName-->"+username);
System.out.println("Password-->"+pwd);
}
@Test(dataProvider="dpmethod")
publicvoid loginAgileEnv(String username, String pwd) {
System.out.println("UserName-->"+username);
System.out.println("Password-->"+pwd);
}

@DataProvider(name="dpmethod")
public Object[][] datapro(Method m){
if(m.getName().equalsIgnoreCase("logintestEnv")){
System.out.println("-----------------test Env -----------------");
returnnew Object[][]{
{ "testnikil", "12345" },
{ "testRaj", "rere" },
{ "testKanti", "Kanti" }
};
}elseif(m.getName().equalsIgnoreCase("loginAgileEnv")){
System.out.println("-----------------Agile Env -----------------");
returnnew Object[][]{
{ "agilnikil", "12345" },
{ "agilproRaj", "rere" },
{ "agilKanti", "Kanti" }
};
}else{
System.out.println("------------Production Env -----------------");
returnnew Object[][]{
{ "pronikil", "12345" },
{ "proRaj", "rere" },
{ "proKanti", "Kanti" }
};
}
}
}


TestNG.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsuiteSYSTEM"http://testng.org/testng-1.0.dtd">
<suitename="Suite"parallel="none"verbose="1"timeOut="1000">
<parametername="MethodName1"value="SuiteTagTestMethod1"/>
<testname="Test1">
<classes>
<classname="testngexp.dpmethodexp"/>
</classes>
</test><!-- Test -->
</suite><!—Suite -->

Results
image

Here, passing different parameter depending on method names, we are using java.lang.reflect.Method

Comments