6

I want to get the name of currently executing TestCase Method in @Before method. Example

public class SampleTest()
{
    @Before
    public void setUp()
    {
        //get name of method here
    }

    @Test
    public void exampleTest()
    {
        //Some code here.
    }
 }
user2508111
  • 261
  • 2
  • 5
  • 8
  • http://stackoverflow.com/questions/473401/get-name-of-currently-executing-test-in-junit-4 ? – ivarni Jun 21 '13 at 08:07
  • add a field `previousName` in your test class and set its value at the end of each test method with After – TecHunter Jun 21 '13 at 08:23

2 Answers2

22

As discussed here, try using @Rule and TestName combination.

As per the documentation before method should have test name.

Annotates fields that contain rules. Such a field must be public, not static, and a subtype of TestRule. The Statement passed to the TestRule will run any Before methods, then the Test method, and finally any After methods, throwing an exception if any of these fail

Here is the test case using Junit 4.9

public class JUnitTest {

    @Rule public TestName testName = new TestName();

    @Before
    public void before() {
        System.out.println(testName.getMethodName());
    }

    @Test
    public void test() {
        System.out.println("test ...");
    }
}
Community
  • 1
  • 1
Jaydeep Patel
  • 2,394
  • 1
  • 21
  • 27
3

Try using a @Rule annotation with org.junit.rules.TestName class

@Rule public TestName name = new TestName();

@Test 
public void test() {
    assertEquals("test", name.getMethodName());
}
darijan
  • 9,725
  • 25
  • 38