May 11th, 2009 Archive

Getting the name of the currently-running test method

May 11th, 2009 by David Saff in Uncategorized

One of the most common requests since JUnit 4.0 was released has been to restore a somewhat accidental feature of JUnit 3.8.  Since, in 3.8, the same object handled test execution and test lifetime management, a test method had access to the getName() method of TestCase, which was internally used for reporting.  Many extenders used this fact to build informed lightweight logging functions.  In JUnit 4.0, this accidental feature was not replicated, which made it difficult to port some of these logging routines.

In the latest snapshot of JUnit 4.7, we’ve re-introduced this feature, by way of Interceptors.  It looks like this:

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

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

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