import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SampleTest { @BeforeAll void setup() { System.out.println("Setup before all tests"); } @Test void testOne() { System.out.println("Test One"); } @Test void testTwo() { System.out.println("Test Two"); } }
The method annotated with @BeforeAll runs once before all test methods in the class. Since the test instance lifecycle is PER_CLASS, the @BeforeAll method can be non-static and will run before any tests.
Therefore, the output starts with "Setup before all tests", followed by the test methods' outputs in the order they run.
import org.junit.jupiter.api.*; public class InitTest { static String sharedResource; @BeforeAll static void init() { sharedResource = "Ready"; } @Test void testResource() { // Which assertion is correct here? } }
The @BeforeAll method initializes sharedResource to "Ready" before any test runs. Therefore, the correct assertion in the test method is to check that sharedResource equals "Ready".
import org.junit.jupiter.api.*; public class ErrorTest { @BeforeAll void setup() { System.out.println("Setup"); } @Test void test() { System.out.println("Test"); } }
In JUnit 5, @BeforeAll methods must be static unless the test class is annotated with @TestInstance(TestInstance.Lifecycle.PER_CLASS). Here, the method is non-static and the class uses default lifecycle, so a runtime error occurs indicating the method should be static.
@BeforeAll is designed to run once before any test methods in the class. It is used to set up expensive or shared resources needed by all tests.
When using @TestInstance(TestInstance.Lifecycle.PER_CLASS), JUnit creates a single test class instance for all tests. This allows @BeforeAll methods to be instance methods (non-static) because the same instance is used.