How to obtain test case name in JUnit 4 at runtime

2019-03-26 03:41发布

This question already has an answer here:

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?

5条回答
走好不送
2楼-- · 2019-03-26 04:19

What's wrong with:

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

?

查看更多
别忘想泡老子
3楼-- · 2019-03-26 04:24

In JUnit 4.7, you can also get the name of the currently executed thest 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());
    }
}
查看更多
叛逆
4楼-- · 2019-03-26 04:26

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()); 
            } 
    } 
查看更多
SAY GOODBYE
5楼-- · 2019-03-26 04:29
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() {
        ...
    }
}
查看更多
Luminary・发光体
6楼-- · 2019-03-26 04:29

I know this is old, but here is a useful (non-junit) method that I put at the top of all my tests.

public static void printTestName(){
    final StackTraceElement[] ste = new Throwable().getStackTrace();
    int buffer = 35 - ste[1].getMethodName().length();
    System.out.println("*******************************************************");
    System.out.println("*            TEST:  " + ste[1].getMethodName() + getBuffer(buffer) + "*");
    System.out.println("*******************************************************");
}

private static String getBuffer(int offset){
    StringBuilder buffer = new StringBuilder("");
    for(int i = 1; i < offset; i++){
        buffer.append(" ");
    }
    return buffer.toString();
}
查看更多
登录 后发表回答