Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `TestInstance(PER_CLASS)` allow `@BeforeAll` methods to not be static?

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.

like image 835
Mikhail Avatar asked Sep 03 '25 04:09

Mikhail


1 Answers

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.

like image 103
Sam Brannen Avatar answered Sep 05 '25 00:09

Sam Brannen