44

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 {...}
}
Meera
  • 455
  • 1
  • 4
  • 12

2 Answers2

68

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)
Wilson
  • 1,259
  • 11
  • 17
  • Another option is: Add file junit-platform.properties and write: junit.jupiter.testinstance.lifecycle.default = per_class – Yani Morales Sep 27 '21 at 14:36
39

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

Sergey
  • 879
  • 1
  • 11
  • 16
  • 2
    I was using @TestInstance(Lifecycle.PER_CLASS). Now I know that was the reason it was allowing me run non-static @beforeAll method. Thank you – Meera Apr 18 '19 at 19:26