1

I would like to retrieve parameters name of Test method in DataProvider method. By using method.getParameterTypes() in DataProvider, I am able to get the class of param being passed in Test method, but I want the names.

@Test
public void TC_001(String userName, String passWord){
//code goes here
}

@DataProvider
public Object[][] testData(Method method){
//Here I want to get names of param of test method i.e. userName and passWord
}

This is required because using these names I can get the data from my Excel file

Barett
  • 5,826
  • 6
  • 51
  • 55
Bhuvan
  • 23
  • 1
  • 6

1 Answers1

0

You can use reflection to get the parameters from the method to get the parameter names.

@DataProvider
public Object[][] testData(Method method){
    String arg0 = method.getParameters()[0].getName();
    // should be "userName" in your example test case
}

Note that the classes have to be compiled with -g:vars to include the parameter names in the debug information. Otherwise parameter names are named arg0, arg1, ... It appears that with the OpenJDK 8 this is the default.

To be less dependant on that fact and to avoid possible name confusion/conflicts I'd use a (custom) annotation that specifies the argument name:

Define an annotation:

@Retention(RUNTIME)
@Target(PARAMETER)
public @interface ParamName {
    public String value();
}

Use it:

public void TC_001(@ParamName("username") String userName, String passWord) { ... }

Access the name:

Parameter parameter = method.getParameters()[0];
ParamName parameterNameAnn = parameter[0].getAnnotation(ParamName.class);
String parameterName;

if (parameterNameAnn != null) {
    // get the annotated name
    parameterName = parameterNameAnn.value();
} else {
    // annotation missing, resort to the "reflected" name
    parameterName = parameter.getName();
}

See also

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67