【问题标题】:Get currently executing @Test method in @Before in JUnit 4在 JUnit 4 中的 @Before 中获取当前正在执行的 @Test 方法
【发布时间】:2013-06-18 10:27:34
【问题描述】:

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

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

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

【问题讨论】:

标签: java junit4


【解决方案1】:

试试 TestName 规则

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

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

【讨论】:

  • 这段代码给出了当前正在执行的方法的名称,并且我们无法将注释应用到它上面。所以我想要实际的方法,然后我想调用 method.getAnnotation(MyAnnotation.class)
  • 如果你有方法名,你可以使用反射来获取实际的方法。
  • 更好的是,您可以编写自己的TestName 版本,它可以获取注释,而不是名称。
  • 感谢 Evgenity Dorofeev 和 Andre。我明白了。
【解决方案2】:

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

public class TestAnnotation extends TestWatcher {
    public MyAnnotation annotation;

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

【讨论】:

    猜你喜欢
    • 2013-06-18
    • 2010-10-03
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2015-01-23
    • 1970-01-01
    相关资源
    最近更新 更多