Junit @AfterClass (non static)

て烟熏妆下的殇ゞ 提交于 2021-01-26 21:57:31

问题


Junit's @BeforeClass and @AfterClass must be declared static. There is a nice workaround here for @BeforeClass. I have a number of unit tests in my class and only want to initialize and clean up once. Any help on how to get a workaround for @AfterClass? I'd like to use Junit without introducing additional dependencies. Thanks!


回答1:


If you want something similar to the workaround mentioned for @BeforeClass, you could keep track of how many tests have been ran, then once all tests have been ran finally execute your ending cleanup code.

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

This assumes you're using JUnit 4. If you need to account for methods inherited from a superclass, see this as this solution does not get inherited methods.



来源:https://stackoverflow.com/questions/37083647/junit-afterclass-non-static

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