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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With