在JUnit 4中的@Before中获取当前正在执行的@Test方法

时间:2013-06-21 10:13:21

标签: java junit4

我想在@Before中获取当前正在执行的测试方法,以便我可以在当前正在执行的方法上应用注释。

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

       @Test
       @MyAnnotation("id")
       public void someTest {
           // code
       }
}         

2 个答案:

答案 0 :(得分:11)

尝试TestName规则

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

  @Before
  public void setUp() {
    Method m = TestCaseExample.class.getMethod(testName.getMethodName());       
    ...
  }
  ...

答案 1 :(得分:3)

Evgeniy指出TestName规则(我从未听说过 - 谢谢,Evgeniy!)。而不是使用它,我建议把它作为你自己的规则的模型,它将捕获感兴趣的注释:

public class TestAnnotation extends TestWatcher {
    public MyAnnotation annotation;

    @Override
    protected void starting(Description d) {
        annotation = d.getAnnotation(MyAnnotation.class);
    }
}
相关问题