I want to set up my JUnit5 tests to all operate on the same object. I read large files to use as test data, so I would prefer to read it once and utilize that same data for the rest of the tests.
I've created the following as a simple example where I try to achieve this using a static object ("list") (does not work):
import java.util.List; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class ExampleTest { // Single list object to be modified and accessed by the tests private static List<String> list = new ArrayList<String>(); @BeforeAll static void setUpBeforeClass() throws Exception { // None } @Test final void addFoo() { list.add("foo"); } @Test final void addBar() { list.add("bar"); } @Test final void printList() { System.out.println(list.toString()); assert(list.toString().equals("[foo, bar]")); } } The result of this is a failure of printList() where the list is empty instead of containing [foo, bar].
I have been able to make this work is by moving the methods that add data into the @BeforeAll:
private static List<String> list; @BeforeAll static void setUpBeforeClass() throws Exception { list = new ArrayList<String>(); list.add("foo"); list.add("bar"); } But having the data importing methods as tests separate from @BeforeAll would be preferred.
@TestInstance(TestInstance.Lifecycle.PER_CLASS) did not work either.
printList()is failing because it gets executed first and the list is empty. Moreover, unit tests should not depend on each other or the order of execution.