使用TestNG中的@BeforeMethod时,有没有一种方法可以获取方法元数据?

21

我正在使用TestNG并拥有一套测试。 我想在每个测试方法之前执行一个需要了解该方法信息的操作。 以一个简单的例子为例,假设我想在执行之前打印方法名称。 我可以编写一个用@BeforeMethod注释的方法。 那么如何向该方法注入参数?

3个回答

27
请查看文档中的依赖注入部分。它指出依赖注入可以在以下情况下使用:
任何@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接口(文档),但由于我不确定如何使用它,如果您感兴趣,我会让您自己看一下。


我正在使用提供多个数据集的数据运行我的测试用例,因此在Extent报告中,同一方法会多次运行,次数与我们在Excel表格中拥有的数据量相同。因此,我想将测试用例名称(即Excel中的变量)作为变量传递给AbstractBaseTestCase类中的before方法,在这种情况下,是否有任何实现该目标的方法? - Arpan Saini

6
以下示例展示了在使用数据提供程序时如何获取参数,可以使用@BeforeMethod中的Object[]数组。
注:@BeforeMethod是TestNG测试框架中的一个注释,用于在每个测试方法之前执行一些共同操作。
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"}
       };
   }
}

这正是我所需要的,用数据提供程序时获取参数。运行得非常完美。 - Nash N
这太棒了! - Samrun0

2
以下示例说明了如何在@Before方法中获取方法名称和类名称。
以下是翻译后的HTML代码:

以下示例说明了如何在@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(){


}   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接