1

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>
Zoette
  • 1,241
  • 2
  • 18
  • 49
  • 2
    You're mixing JUnit 4 dependencies, JUnit Jupiter dependencies and TestNG annotation... – Mureinik Dec 27 '19 at 04:11
  • Yup I reckon I've been trying several things... any idea on how I could get the method's name? – Zoette Dec 29 '19 at 08:48
  • (Yet your post helped me understand from where the problem could come, thus I give you +1. Thank you) – Zoette Dec 30 '19 at 03:25

2 Answers2

1

As noted in the comments, the question mixes JUnit 4, JUnit Jupiter (JUnit 5) and TestNG, and you probably want to focus on just one.

In JUnit Jupiter, this information is accessible via the ExtensionContext. I'm not aware of a built-in extension that just prints it, but it's quite easy to write one yourself:

public class NamePrinter implements BeforeEachCallback {
    @Override
    public void beforeEach(ExtensionContext extensionContext) throws Exception {
        extensionContext.getTestMethod().ifPresent(m -> System.out.println(
                "Running method: " + m.getName() + 
                " [display name: " + extensionContext.getDisplayName() + ")"));
    }
}

And then you can just use it as an extension:

@ExtendWith(NamePrinter.class)
public class MyClassTest {

    @Test
    public void someTest() {
        System.out.println("This is a test");
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

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(); 
    }

}
Zoette
  • 1,241
  • 2
  • 18
  • 49