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

流过昼夜 提交于 2019-12-06 01:59:57

问题


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
       }
}         

回答1:


try TestName rule

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

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



回答2:


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);
    }
}


来源:https://stackoverflow.com/questions/17232715/get-currently-executing-test-method-in-before-in-junit-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!