Search code examples
javajunit5

@BeforeAll Method as non-static


I was able to implement a non-static setup method with @BeforeAll annotation. It seems to be working correctly as it only gets called once. I am bit confused, as the documentation for @BeforeAll says the method has to be static. Can someone explain to me why my setup works anyway?

My code:

@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 {...}
}

Solution

  • 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)