Here is my test class
@SpringBootTest
@ActiveProfiles("test")
public MyTest {
...
@Before
public void init() {
System.out.println(":::: --- start init() ---");
...
}
...
}
Strange enough, the init()
won't run for some reason. If I change the @Before
to @BeforeAll
and the method to static, the init()
will run. A problem is that those data set up code doesn't run inside a static method and I can't change all of them to run inside a static block. For now, I have the following code in each test method to overcome the issue
if(list.size() == 0)
init();
I am wondering why the @Before
won't run. Any advice?
In JUnit 5, @BeforeEach
and @BeforeAll
annotations are the equivalents for @Before
and @BeforeClass
in JUnit 4.
@Before
is a JUnit 4 annotation, while @BeforeAll
is a JUnit 5 annotation. You can also see this from the imports org.junit.Before
and org.junit.jupiter.api.BeforeAll
.
Also, the code marked @BeforeEach
is executed before each test, while @BeforeAll
runs once before the entire test fixture.
To be able to run @BeforeAll
on a non-static method you can change the lifecycle of the the test instance with:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
You have to be careful though, since the test class instance is now only created once, and not once per test method. If your test methods rely on state stored in instance variables, you may now need to manually reset the state in @BeforeEach
or @AfterEach
lifecycle methods.