1

我想在 DataProvider 方法中检索 Test 方法的参数名称。通过method.getParameterTypes()在 DataProvider 中使用,我可以获得在 Test 方法中传递的参数类,但我想要名称。

@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
}

这是必需的,因为使用这些名称我可以从我的 Excel 文件中获取数据

4

1 回答 1

0

您可以使用反射从方法中获取参数以获取参数名称。

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

请注意,必须编译类以-g:vars在调试信息中包含参数名称。否则,参数名称将命名为arg0, arg1, ... 似乎在 OpenJDK 8 中这是默认设置。

为了减少对该事实的依赖并避免可能的名称混淆/冲突,我将使用指定参数名称的(自定义)注释:

定义注解:

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

用它:

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

访问名称:

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();
}

也可以看看

于 2017-06-18T14:06:35.237 回答