Junit @AfterClass(非静态) [英] Junit @AfterClass (non static)

查看:57
本文介绍了Junit @AfterClass(非静态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!

推荐答案

如果您想要的内容与@BeforeClass中提到的解决方法类似,则可以跟踪已运行了多少测试,然后一旦运行了所有测试最后执行结束清理代码.

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

这假定您正在使用JUnit4.如果需要考虑从超类继承的方法,请参见

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.

这篇关于Junit @AfterClass(非静态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆