我正在使用TestNG并拥有一套测试。 我想在每个测试方法之前执行一个需要了解该方法信息的操作。 以一个简单的例子为例,假设我想在执行之前打印方法名称。 我可以编写一个用@BeforeMethod
注释的方法。 那么如何向该方法注入参数?
我正在使用TestNG并拥有一套测试。 我想在每个测试方法之前执行一个需要了解该方法信息的操作。 以一个简单的例子为例,假设我想在执行之前打印方法名称。 我可以编写一个用@BeforeMethod
注释的方法。 那么如何向该方法注入参数?
@BeforeMethod
(和@AfterMethod
)都可以声明一个类型为java.lang.reflect.Method
的参数。该参数将接收测试方法,该方法将在此@BeforeMethod
完成后调用(或在运行@AfterMethod
方法后调用)。@BeforeMethod
中声明一个类型为java.lang.reflect.Method
的参数,就可以访问以下测试名称。例如:@BeforeMethod
protected void startTest(Method method) throws Exception {
String testName = method.getName();
System.out.println("Executing test: " + testName);
}
还有一种方法是使用ITestNGMethod
接口(文档),但由于我不确定如何使用它,如果您感兴趣,我会让您自己看一下。
public class TestClass {
@BeforeMethod
public void beforemethod(Method method, Object[] params){
String classname = getClass().getSimpleName();
String methodName = method.getName();
String paramsList = Arrays.asList(params).toString();
}
@Test(dataProvider = "name", dataProviderClass = DataProvider.class)
public void exampleTest(){...}
}
public class DataProvider {
@DataProvider(name = "name")
public static Object[][] name() {
return new Object[][]{
{"param1", "param2"},
{"param1", "param2"}
};
}
}
以下示例说明了如何在@Before方法中获取方法名称和类名称。
@BeforeMethod
public void beforemethod(Method method){
//if you want to get the class name in before method
String classname = getClass().getSimpleName();
//IF you want to get the method name in the before method
String methodName = method.getName()
}
@Test
public void exampleTest(){
}