I have read documentation, there is no need to explain, how we can access non-static felds in BeforeAll method etc. I am looking for an answer - why TestInstance(PER_CLASS) solve static in the method signature BeforeAll method? In other words - how does it internally works? There is no explaination about it in official docs, just said
@BeforeAll methods must have a void return type, must not be private, and must be static by default. Consequently, @BeforeAll methods are not supported in @Nested test classes or as interface default methods unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS)
And that is all. It is not clear, not obvious. Suppose, I do not understand something.
As stated in the Javadoc for PER_CLASS
:
When using this mode, a new test instance will be created once per test class.
In other words, when using test instance PER_CLASS
semantics, there is one instance of the test class that is reused for the invocations of all test methods in that class.
In order to do that, JUnit must instantiate that single test instance in advance (before invoking @BeforeAll
methods). Consequently, since JUnit already has an instance of the class, @BeforeAll
methods do not have to be static
: JUnit will invoke @BeforeAll
methods on that single instance. The same applies to @AfterAll
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