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
  • 46,221
  • 15
  • 164
  • 151
user2508111
  • 261
  • 2
  • 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

16

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
  • 133,369
  • 30
  • 199
  • 275
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
  • 46,189
  • 17
  • 92
  • 133