jamesw1234
jamesw1234

Reputation: 338

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!

Upvotes: 11

Views: 9519

Answers (1)

kingkupps
kingkupps

Reputation: 3494

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.

Upvotes: 4

Related Questions