@AfterEach
is used to signal that the annotated method should be
executed after each @Test
,
@RepeatedTest
, @ParameterizedTest
, @TestFactory
,
and @TestTemplate
method in the current test class.
Method Signatures
@AfterEach
methods must have a void
return type and must
not be static
. In addition, @AfterEach
methods may optionally
declare parameters to be resolved by
ParameterResolvers
.
Using private
visibility for @AfterEach
methods is strongly
discouraged and will be disallowed in a future release.
Inheritance and Execution Order
@AfterEach
methods are inherited from superclasses as long as they
are not overridden according to the visibility rules of the Java
language. Furthermore, @AfterEach
methods from superclasses will be
executed after @AfterEach
methods in subclasses.
Similarly, @AfterEach
methods declared as interface default
methods are inherited as long as they are not overridden, and
@AfterEach
default methods will be executed after @AfterEach
methods in the class that implements the interface.
JUnit Jupiter does not guarantee the execution order of multiple
@AfterEach
methods that are declared within a single test class or
test interface. While it may at times appear that these methods are invoked
in alphabetical order, they are in fact sorted using an algorithm that is
deterministic but intentionally non-obvious.
In addition, @AfterEach
methods are in no way linked to
@BeforeEach
methods. Consequently, there are no guarantees with
regard to their wrapping behavior. For example, given two
@BeforeEach
methods createA()
and createB()
as well
as two @AfterEach
methods destroyA()
and destroyB()
,
the order in which the @BeforeEach
methods are executed (e.g.
createA()
before createB()
) does not imply any order for the
seemingly corresponding @AfterEach
methods. In other words,
destroyA()
might be called before or after
destroyB()
. The JUnit Team therefore recommends that developers
declare at most one @BeforeEach
method and at most one
@AfterEach
method per test class or test interface unless there are
no dependencies between the @BeforeEach
methods or between the
@AfterEach
methods.
Composition
@AfterEach
may be used as a meta-annotation in order to create
a custom composed annotation that inherits the semantics of
@AfterEach
.
- Since:
- 5.0
- See Also: