Junit @AfterClass(非静态)

jam*_*234 9 java junit spring unit-testing

Junit @BeforeClass@AfterClass必须声明为静态.有一个很好的解决办法在这里进行@BeforeClass.我班上有很多单元测试,只想初始化和清理一次.有关如何获得解决方法的任何帮助@AfterClass?我想在不引入其他依赖项的情况下使用Junit.谢谢!

kin*_*pps 4

如果您想要类似于提到的解决方法@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...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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