Getting the name of the currently-running test method

Written on Monday, May 11th, 2009 at 11:04 pm by David Saff
Filed under 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:

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

Leave a Reply

You must be logged in to post a comment.