Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get method meta data when using @BeforeMethod in TestNG?

I am using TestNG and have a suite of tests. I want to perform an action before every test method that requires information about the method. As a simple example, say I want to print the name of the method before its executed. I can write a method annotated with @BeforeMethod. How can I inject parameters into that method?

like image 442
Usman Ismail Avatar asked Dec 12 '11 16:12

Usman Ismail


3 Answers

Take a look at the dependency injection section in the documentation. It states that dependency injection can be used for example in this case:

Any @BeforeMethod (and @AfterMethod) can declare a parameter of type java.lang.reflect.Method. This parameter will receive the test method that will be called once this @BeforeMethod finishes (or after the method as run for @AfterMethod).

So basically you just have to declare a parameter of type java.lang.reflect.Method in your @BeforeMethod and you will have access to the name of the following test name. Something like:

@BeforeMethod
protected void startTest(Method method) throws Exception {
    String testName = method.getName(); 
    System.out.println("Executing test: " + testName);
}

There's also a way by using the ITestNGMethod interface (documentation), but as I'm not exactly sure on how to use it, I'll just let you have a look at it if you're interested.

like image 100
talnicolas Avatar answered Nov 20 '22 14:11

talnicolas


Below example shows how to get params when using data provider, using Object[] array in @BeforeMethod.

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"}
       };
   }
}
like image 20
Fede Ogrizovic Avatar answered Nov 20 '22 13:11

Fede Ogrizovic


Below example explains how you can get the method name and class name in your before Method

@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(){


}   
like image 2
Arpan Saini Avatar answered Nov 20 '22 14:11

Arpan Saini