What is the correct order of printed lines when running this test class?
medium
A. InitAll, Init, TestOne, TearDown, Init, TestTwo, TearDown, TearDownAll
B. Init, InitAll, TestOne, TearDown, TestTwo, Init, TearDownAll
C. InitAll, Init, TestOne, Init, TestTwo, TearDown, TearDownAll, TearDown
D. InitAll, TestOne, Init, TearDown, Init, TestTwo, TearDown, TearDownAll
Solution
Step 1: Understand lifecycle method order
@BeforeAll runs once before all tests, then for each test @BeforeEach runs, test runs, then @AfterEach runs. Finally, @AfterAll runs once after all tests.
Step 2: Apply to given methods
Output order: InitAll (once), then for testOne: Init, TestOne, TearDown; for testTwo: Init, TestTwo, TearDown; finally TearDownAll.
In JUnit 5, @BeforeAll methods must be static unless using a test instance lifecycle that allows non-static.
Step 2: Check method signature
The method 'setupAll' is not static, which causes a runtime error or test failure.
Final Answer:
@BeforeAll method must be static. -> Option B
Quick Check:
@BeforeAll requires static method by default [OK]
Hint: @BeforeAll methods are static unless configured otherwise [OK]
Common Mistakes:
Making @BeforeAll non-static without lifecycle config
Assuming @BeforeAll can be private
Thinking @BeforeAll must return a value
5. You want to open a database connection once before all tests and close it once after all tests in a JUnit 5 test class. You also want to reset some data before each test and clean up after each test. Which combination of lifecycle methods should you use?
hard
A. @BeforeAll for resetting data, @AfterAll for cleanup, @BeforeEach for opening connection, @AfterEach for closing connection
B. @BeforeEach for opening connection, @AfterEach for closing connection, @BeforeAll for resetting data, @AfterAll for cleanup
C. @BeforeAll for opening connection, @AfterAll for closing connection, @BeforeEach for resetting data, @AfterEach for cleanup
D. @BeforeEach for resetting data, @AfterEach for cleanup, @BeforeAll for opening connection, @AfterAll for closing connection
Solution
Step 1: Assign tasks to lifecycle methods
Opening and closing the database connection should happen once, so use @BeforeAll and @AfterAll.
Step 2: Use per-test methods for data reset and cleanup
Resetting data and cleaning up should happen before and after each test, so use @BeforeEach and @AfterEach.
Final Answer:
@BeforeAll for opening connection, @AfterAll for closing connection, @BeforeEach for resetting data, @AfterEach for cleanup -> Option C
Quick Check:
Once methods for setup/teardown, each methods for per-test tasks [OK]
Hint: Once = BeforeAll/AfterAll, each test = BeforeEach/AfterEach [OK]
Common Mistakes:
Opening connection before each test unnecessarily
Resetting data only once before all tests
Closing connection after each test causing overhead
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.