views:

826

answers:

3

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?

A: 

What's wrong with:

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

?

Grzegorz Oledzki
In JUnit 4 the test classes no longer extend a common framework class. So there's no inherited method getName any more.
mkoeller
OK. I still don't get what is the `this.getName() about. How is it different than this.getClass().getName()?(I've found another answer for you)
Grzegorz Oledzki
In JUnit 3, TestCase.getName() returns the name of the test method. When you run a JUnit3 test case, multiple instances of your test class are created, each with a different name. See http://junit.sourceforge.net/doc/cookstour/cookstour.htm
NamshubWriter
+4  A: 

OK. I've found another approach somewhere on the Internet:

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

            @Test public void funnyName() { 
                    assertEquals("funnyName", name.getMethodName()); 
            } 
    }
Grzegorz Oledzki
That seems exactly in the direction I was looking for. I'll give it a try tomorrow.
mkoeller
Unfortunately, this solution is only going to be released in the upcoming final version of JUnit 4.7 . Meanwhile I'm forced to stick with an earlier version that's included in the customer's framework architecture.However, this is the best answer to the question.
mkoeller
+1  A: 

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