有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Junit@AfterClass(非静态)

Junit的@BeforeClass@AfterClass必须声明为静态。对于@BeforeClass,有一个很好的解决方法here。我的类中有很多单元测试,只想初始化和清理一次。关于如何找到@AfterClass的解决方法,有什么帮助吗?我希望在不引入额外依赖项的情况下使用Junit。谢谢


共 (1) 个答案

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

    这假设您使用的是JUnit4。如果需要说明从超类继承的方法,请参见this,因为此解决方案不会获得继承的方法