Complete the code to use the correct annotation for a nested test class lifecycle.
import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.[1]) @Nested class InnerTest { @Test void testMethod() { Assertions.assertTrue(true); } }
By default, nested test classes in JUnit use PER_METHOD lifecycle, which creates a new instance for each test method.
Complete the code to annotate a nested test class that shares the same instance for all tests.
import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.[1]) @Nested class SharedInstanceTest { int counter = 0; @Test void testIncrement() { counter++; Assertions.assertTrue(counter > 0); } }
Using PER_CLASS lifecycle means the same instance of the nested test class is used for all test methods, allowing state sharing.
Fix the error in the nested test class lifecycle annotation to make the code compile.
import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.[1]) @Nested class ErrorTest { @Test void testSomething() { Assertions.assertEquals(1, 1); } }
The option INSTANCE is invalid. The correct lifecycle options are PER_CLASS or PER_METHOD. Here, PER_CLASS is the fix to compile.
Fill both blanks to create a nested test class with a per-class lifecycle and a setup method that runs once before all tests.
import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.[1]) @Nested class SetupTest { @Before[2] void init() { System.out.println("Setup before all tests"); } @Test void testOne() { Assertions.assertTrue(true); } }
Using PER_CLASS lifecycle allows the use of @BeforeAll on non-static methods in nested classes.
Fill all three blanks to define a nested test class with per-class lifecycle, a non-static @BeforeAll method, and a test method that asserts a counter increments.
import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.[1]) @Nested class CounterTest { int counter = 0; @Before[2] void setup() { counter = 1; } @Test void testIncrement() { counter[3]; Assertions.assertEquals(2, counter); } }
With PER_CLASS lifecycle, @BeforeAll can be non-static. The counter is incremented with ++ to reach 2.