Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain test case name in JUnit 4 at runtime? [duplicate]

I want to do some logging while executing my JUnit test. In JUnit 3.x it was always easy to obtain the name of the currently running test case, no matter how the test case was instantiated:

public void testFoo() throws Exception() {
  String testName = this.getName();
  // [...] do some stuff
}

In JUnit 4 things seem to be not so easy. Does anyone know a solution to this? Is there any option to reflect into the current Runner instance?

like image 924
mkoeller Avatar asked Jul 01 '09 14:07

mkoeller


3 Answers

In JUnit 4.7, you can also get the name of the currently executed test method. May be nice when logging.

Taken from JUnit 4.7 Release Notes (read them here at github) :

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());
    }
}
like image 184
Sebastian Schuth Avatar answered Sep 19 '22 04:09

Sebastian Schuth


OK. I've found another approach [somewhere on the Internet](http://www.nabble.com/What-happened-to-getName()--td23456371.html):

    @RunWith(Interceptors.class) 
    public class NameTest { 
            @Interceptor public TestName name = new TestName(); 

            @Test public void funnyName() { 
                    assertEquals("funnyName", name.getMethodName()); 
            } 
    } 
like image 21
Grzegorz Oledzki Avatar answered Sep 19 '22 04:09

Grzegorz Oledzki


public class FooTest {
    @Rule
    final public TestRule traceTestWatcher = new TestWatcher() {
        @Override
        protected void starting(Description d) {
            System.out.println(d);
        }
    };

    @Test
    public void testBar() {
        ...
    }

    @Test
    public void testBaz() {
        ...
    }
}
like image 31
Peter Tseng Avatar answered Sep 20 '22 04:09

Peter Tseng