Search code examples
javamavenseleniumjunitjunit-rule

JUnit getMethodName returns null


I'm running some Selenium tests and I'm not able to access my test methods' names. I would like to print something in the logs like "Starting test: foobarbaz"

All my test classes inherit a public "AbstractTest" class, which contains:

@Rule TestName name = new TestName();

@BeforeTest
public void testSetUp(){
    System.out.println(name);
    System.out.println(name.getMethodName());
}

But the output is:

org.junit.rules.TestName@59f63e24
null

Why is getMethodName() method returning null?

An extract of my pom.xml that may be useful...

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.5.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.5.2</version>
    <scope>test</scope>
</dependency>

Solution

  • The TestNG solution worked (found it in another thread): https://stackoverflow.com/a/12202455/7093031

    import java.lang.reflect.Method;
    
    public class Test {
    
        @BeforeMethod
        public void handleTestMethodName(Method method){
            String testName = method.getName(); 
        }
    
    }