Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@BeforeAll Method as non-static

Tags:

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 {...} } 
like image 791
Meera Avatar asked Apr 17 '19 02:04

Meera


People also ask

Does BeforeAll have to be static?

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

Does BeforeClass have to be static?

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.

What is order of execution of JUnit lifecycle callbacks?

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.


2 Answers

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) 
like image 120
Wilson Avatar answered Sep 29 '22 20:09

Wilson


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

like image 26
Sergey Avatar answered Sep 29 '22 19:09

Sergey