9

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
       }
}         
Ali Dehghani
  • 43,096
  • 14
  • 154
  • 142
user2508111
  • 231
  • 1
  • 5
  • 8
  • See http://stackoverflow.com/questions/473401/get-name-of-currently-executing-test-in-junit-4 for some more discussion about this – centic Oct 28 '14 at 16:41

2 Answers2

15

try TestName rule

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

  @Before
  public void setUp() {
    Method m = TestCaseExample.class.getMethod(testName.getMethodName());       
    ...
  }
  ...
Evgeniy Dorofeev
  • 129,181
  • 28
  • 195
  • 266
3

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);
    }
}
Tom Anderson
  • 44,913
  • 16
  • 86
  • 129