TransWikia.com

Get class name of the calling class

Software Quality Assurance & Testing Asked on November 21, 2021

I needed to get a class name from my calling class. I will not make too much confusion.

I have 3 classes .

Class A{ //do something } 

Class B extends Class A 
{ 
     @Test(dataProvider = "dp" , dataProviderClass = C.class)
     public void methodone(String name)
     {
       //do something
     }
} 


Class C extends Class A 
{
    @DataProvider(name="dp")
    public Object[][] getData(Method m) {
        String sheetName = m.getName();
        System.out.println("---"+sheetName); }
} 

In the Class C, i need the name of the calling class to be printed . But for now it is printing the name of the calling method which is "methodone" of class B. But i need as "class B" to be printed. Can some one help. Thank you.

2 Answers

Just to add to the above answer,

If you refer the documentation

https://testng.org/doc/documentation-main.html#parameters-dataproviders

If you declare your @DataProvider as taking a java.lang.reflect.Method as first parameter, 

so whatever class methods supported for java.lang.reflect.Method class will be supported inside the data provider, you can see all the available methods at:

https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html

Answered by PDHide on November 21, 2021

This will help you

public class Dummy {
    @DataProvider(name="dp")
    public Object[][] getData(Method m) {
        //this will print respective class name
        System.out.println(m.getDeclaringClass());
        return new Object[][] {{"name"}};
    }
}

Will print the class name as shown in image below enter image description here

You can get only the class name by applying the split feature over the extracted string

Using split function to get the class name

@DataProvider(name="dp")
    public Object[][] getData(Method m) {
        String classname=m.getDeclaringClass().toString().split(" ")[1];
        System.out.println(classname.split("\.")[classname.split("\.").length-1]);
        return new Object[][] {{"Testing is awesome"}};
    }

Using inbuilt function to get the class name

@DataProvider(name="dp")
    public Object[][] getData(Method m) {
        String classname=m.getDeclaringClass().getSimpleName();
        System.out.println(classname);
        return new Object[][] {{"Testing is awesome"}};
    }

Answered by Mohamed Sulaimaan Sheriff on November 21, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP