Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get currently executing @Test method in @Before in JUnit 4

Tags:

java

junit4

I want to get currently executing test method in @Before so that I can get the annotation applied on currently executing method.

public class TestCaseExample {
       @Before
       public void setUp() {
           // get current method here.
       }

       @Test
       @MyAnnotation("id")
       public void someTest {
           // code
       }
}         
like image 662
user2508111 Avatar asked Jun 21 '13 10:06

user2508111


2 Answers

try TestName rule

public class TestCaseExample {
  @Rule
  public TestName testName = new TestName();

  @Before
  public void setUp() {
    Method m = TestCaseExample.class.getMethod(testName.getMethodName());       
    ...
  }
  ...
like image 109
Evgeniy Dorofeev Avatar answered Oct 25 '22 02:10

Evgeniy Dorofeev


Evgeniy pointed to the TestName rule (which i'd never heard of - thanks, Evgeniy!). Rather than using it, i suggest taking it as a model for your own rule which will capture the annotation of interest:

public class TestAnnotation extends TestWatcher {
    public MyAnnotation annotation;

    @Override
    protected void starting(Description d) {
        annotation = d.getAnnotation(MyAnnotation.class);
    }
}
like image 26
Tom Anderson Avatar answered Oct 25 '22 03:10

Tom Anderson