@AfterClass

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

The annotation must be attached to a static method.

@AfterClass and Class Hierarchies

If two methods with different names are annotated with @AfterClass in a test class hierarchy, as shown below:

TestBase.java
  │  @AfterClass
  │  public static void testBaseOneTimeTeardown() {
  │     ...
  │  }
  │
  └── SomeTest.java
        @AfterClass
        public static void someTestOneTimeTeardown() {
          ...
        }

then both methods are executed only once, in this order: first the subclass method (someTestOneTimeTeardown()), then the parent class method (testBaseOneTimeTeardown()). The rule holds true in a multi-layer hierarchy.

However, if both methods have the same name, an override of sorts takes place and only the method belonging to the subclass is executed:

TestBase.java
  │  @AfterClass
  │  public static void oneTimeClassTeardown() {
  │     ...
  │  }
  │
  └── SomeTest.java
        @AfterClass
        public static void oneTimeClassTeardown() {
          ...
        }

Only SomeTest.oneTimeClassTeardown() (the most specific subclass) is executed, so if you need the logic executed in superclass, it must be invoked explicitly with:

class SomeTest {
  @AfterClass
  public static void oneTimeClassTeardown() {
     TestBase.oneTimeClassTeardown();
  }
}

In conclusion, if class-level one-time cleanup is needed for each level of a class hierarchy, the best solution is to name @AfterClass methods differently for each class. This way, all methods are executed in order, starting from the bottom of the hierarchy (the most specific subclass) and continuing in order towards the root of the hierarchy.

Recommended naming convention:

class SomeTest {
  @AfterClass
  public static void someTestOneTimeTeardown() {
     ...
  }
}