Dave Ray Dave Ray - 1 year ago 77
Java Question

Get name of currently executing test in JUnit 4

In JUnit 3, I could get the name of the currently running test like this:

public class MyTest extends TestCase
public void testSomething()
System.out.println("Current test is " + getName());

which would print "Current test is testSomething".

Is there any out-of-the-box or simple way to do this in JUnit 4?

Background: Obviously, I don't want to just print the name of the test. I want to load test-specific data that is stored in a resource with the same name as the test. You know, convention over configuration and all that.


Answer Source

JUnit 4.7 added this feature it seems using TestName-Rule. Looks like this will get you the method name:

import org.junit.Rule;

public class NameRuleTest {
    @Rule public TestName name = new TestName();

    @Test public void testA() {
        assertEquals("testA", name.getMethodName());

    @Test public void testB() {
        assertEquals("testB", name.getMethodName());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download