Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why methods annotated with @BeforeAll and @AfterAll should be static in JUnit 5?

I know that methods annotated with @BeforeAll and @AfterAll JUnit 5 annotations should be static unless TestInstance.Lifecycle.PER_CLASS is used.

What I can't understand is why JUnit 5 imposes such limitations? If it is allowed with PER_CLASS lifecycle, what changes drastically when using PER_METHOD?

Thanks in advance.

like image 389
zer_ik Avatar asked Oct 23 '25 17:10

zer_ik


1 Answers

When you use PER_METHOD, a new instance of the test class is created for each test method. Methods annotated with @BeforeAll would need to be called before any instance is created. Likewise, @AfterAll needs to be called after all tests are done, and therefore no instance is available anymore. That lack of instances means these methods need to be static.

like image 140
Rob Spoor Avatar answered Oct 26 '25 05:10

Rob Spoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!