I was able to implement a non-static setup method with @BeforeAll
annotation. It seems to be working correctly as only gets call once. I am bit confuse as the documentation for @BeforeAll
says the method has to be static. Please explain.
@TestMethodOrder(OrderAnnotation.class) @SpringJUnitWebConfig(locations = { "classpath:service.xml" }) @TestInstance(Lifecycle.PER_CLASS) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Inherited public class MyTest { @BeforeAll public void setup() throws Exception {...} }
@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.
JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods. However, this cannot be used with dependency injection.
In JUnit 5, the test lifecycle is driven by four primary annotations i.e. @BeforeAll, @BeforeEach, @AfterEach and @AfterAll. Along with it, each test method must be marked with @Test annotation from package org. junit.
You simply need to annotate your test class (that contains the @BeforeAll
method) with the snippet below and you'll be good to go.
@TestInstance(Lifecycle.PER_CLASS)
If you want use non-static @BeforeAll
and @AfterAll
methods you should change test instance lifecycle to per_class
.
Look there: 2.10. Test Instance Lifecycle
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