【问题标题】:Junit @AfterClass (non static)Junit @AfterClass(非静态)
【发布时间】:2016-09-02 04:36:48
【问题描述】:

Junit 的 @BeforeClass@AfterClass 必须声明为静态的。 @BeforeClass 有一个很好的解决方法here。我的班级中有许多单元测试,只想初始化和清理一次。关于如何获得@AfterClass 的解决方法的任何帮助?我想在不引入额外依赖项的情况下使用 Junit。谢谢!

【问题讨论】:

  • 是什么阻止您使用静态方法来设置和拆除?没错,您设置的状态必须移动到静态字段,但听起来您希望它具有静态范围。
  • 将测试实例保存在static 字段中。在您的 @AfterClass 方法中访问它并让它调用您想要的任何清理方法。
  • 还有其他类访问需要不同作用域的相同清理方法
  • 听起来您应该将 setup 和 teardown 方法重构为 JUnit Rule。然后,您可以进行在静态上下文中使用它的测试和在非静态上下文中使用它的测试。
  • 你找到这个问题的答案了吗?

标签: java spring unit-testing junit


【解决方案1】:

如果您想要类似于@BeforeClass 提到的解决方法,您可以跟踪已经运行了多少测试,然后在运行所有测试后最终执行您的结束清理代码。

public class MyTestClass {
  // ...
  private static int totalTests;
  private int testsRan;
  // ...

  @BeforeClass
  public static void beforeClass() {
    totalTests = 0;
    Method[] methods = MyTestClass.class.getMethods();
    for (Method method : methods) {
      if (method.getAnnotation(Test.class) != null) {
        totalTests++;
      }
    }
  }

  // test cases...

  @After
  public void after() {
    testsRan++;
    if (testsRan == totalTests) {
       // One time clean up code here...
    }
  }
}

这假设您使用的是 JUnit 4。如果您需要考虑从超类继承的方法,请参阅 this,因为此解决方案没有继承方法。

【讨论】:

  • 这可能在简单的情况下有效,但如果测试被忽略或在继承的测试中无效
  • @dkatzel 好点。您还可以通过执行类似this 的操作来遍历继承的方法。最好将只应清理一次的资源保持为静态并在@AfterClass 期间处理它。
猜你喜欢
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 2011-11-14
  • 2010-12-27
  • 1970-01-01
相关资源
最近更新 更多