import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class OuterTest { @BeforeAll void beforeAllOuter() { System.out.println("BeforeAll Outer"); } @Test void outerTest() { System.out.println("Outer Test"); } @Nested class InnerTest { @BeforeAll void beforeAllInner() { System.out.println("BeforeAll Inner"); } @Test void innerTest() { System.out.println("Inner Test"); } } }
The @BeforeAll method in the outer class runs first, printing "BeforeAll Outer". Then the outer test runs, printing "Outer Test". Next, the nested class's @BeforeAll runs before its tests, printing "BeforeAll Inner". Finally, the nested test runs, printing "Inner Test".
import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class FlagTest { boolean flag = false; @Nested class Inner { @Test void setFlag() { flag = true; } } }
assertTrue(flag); is the correct assertion to verify that the boolean flag is true after the nested test sets it.
import org.junit.jupiter.api.*; public class SampleTest { @Nested class Inner { @BeforeAll static void setup() { System.out.println("Setup Inner"); } @Test void test() { System.out.println("Test Inner"); } } }
In JUnit 5, @BeforeAll methods must be static by default. For nested classes, if the outer class does not use @TestInstance(Lifecycle.PER_CLASS), the @BeforeAll method inside the nested class must be static. Otherwise, it will not run.
@Nested allows grouping related tests inside inner classes, improving organization and readability by logically grouping tests that share setup or context.
When using @TestInstance(Lifecycle.PER_CLASS), JUnit creates one instance of the test class per class, allowing @BeforeAll methods to be non-static. This applies to nested classes as well, so their @BeforeAll methods can be instance methods and run once per class instance.