Junit @AfterClass (non-static)

Junit @BeforeClass and @AfterClass must be declared static. There is a nice workaround here for @BeforeClass . I have several unit tests in my class and only want to initialize and clear once. Any help on how to get a workaround for @AfterClass ? I would like to use Junit without introducing additional dependencies. Thanks!

+7
java spring unit-testing junit
source share
1 answer

If you need something similar to the workaround mentioned for @BeforeClass , you can keep track of how many tests have been run, and then once all the tests have been run, finally execute your final 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... } } } 

It is assumed that you are using JUnit 4. If you need to consider methods inherited from the superclass, see this , as this solution does not get the inherited methods.

0
source share

All Articles