Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of currently executing @Test method in @Before in JUNIT [duplicate]

Tags:

java

junit

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.
    }
 }
like image 531
user2508111 Avatar asked Jun 21 '13 08:06

user2508111


2 Answers

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 ...");
    }
}
like image 170
Jaydeep Patel Avatar answered Nov 14 '22 20:11

Jaydeep Patel


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());
}
like image 37
darijan Avatar answered Nov 14 '22 22:11

darijan