Hint: Check method parameters match interface exactly [OK]
Common Mistakes:
Omitting ExtensionContext parameter
Making method static incorrectly
Thinking BeforeEachCallback is mandatory
Believing print statements are disallowed
5. You want to create a JUnit 5 extension that logs the start time before each test and logs the elapsed time after each test. Which approach correctly uses BeforeEachCallback and AfterEachCallback to achieve this?
hard
A. Store start time in a field in beforeEach, then calculate elapsed time in afterEach using the same field
B. Store start time in a local variable inside beforeEach and reuse it in afterEach
C. Use static variables to store start time shared across all tests
D. Only implement BeforeEachCallback and log elapsed time after test in test method
Solution
Step 1: Understand lifecycle of BeforeEachCallback and AfterEachCallback
They run before and after each test method, so storing start time in a field allows sharing data between these callbacks for the same test.
Step 2: Evaluate options for storing start time
Local variables in beforeEach cannot be accessed in afterEach; static variables cause data sharing issues across tests; logging elapsed time in test method breaks separation of concerns.
Final Answer:
Store start time in a field in beforeEach, then calculate elapsed time in afterEach using the same field -> Option A
Quick Check:
Use instance field to share data between beforeEach and afterEach [OK]
Hint: Use instance fields to share data between callbacks [OK]
Common Mistakes:
Trying to share data via local variables
Using static fields causing test interference
Logging elapsed time inside test methods
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.