Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit @AfterClass (non static)

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!

like image 566
jamesw1234 Avatar asked May 07 '16 01:05

jamesw1234


1 Answers

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.

like image 57
kingkupps Avatar answered Oct 25 '22 11:10

kingkupps