Bird
Raised Fist0
JUnittesting~20 mins

BeforeEachCallback and AfterEachCallback in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
JUnit Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Purpose of BeforeEachCallback in JUnit 5
What is the main purpose of implementing the BeforeEachCallback interface in a JUnit 5 extension?
ATo execute code only if a test fails
BTo execute code once before all tests in a test class run
CTo execute code after each test method runs
DTo execute code before each individual test method runs
Attempts:
2 left
💡 Hint
Think about when you want to prepare the test environment for every test method.
🧠 Conceptual
intermediate
1:30remaining
Difference between BeforeEachCallback and AfterEachCallback
Which statement correctly describes the difference between BeforeEachCallback and AfterEachCallback in JUnit 5?
ABeforeEachCallback runs before each test; AfterEachCallback runs after each test
BBeforeEachCallback runs after each test; AfterEachCallback runs before each test
CBoth run before each test but in different threads
DBoth run after all tests have finished
Attempts:
2 left
💡 Hint
Think about setup and cleanup around each test.
❓ Predict Output
advanced
2:00remaining
Output of JUnit Extension with BeforeEachCallback and AfterEachCallback
Given the following JUnit 5 extension code, what will be printed to the console when running a test method using this extension?
JUnit
import org.junit.jupiter.api.extension.*;

public class MyExtension implements BeforeEachCallback, AfterEachCallback {
    @Override
    public void beforeEach(ExtensionContext context) {
        System.out.println("Setup before test");
    }

    @Override
    public void afterEach(ExtensionContext context) {
        System.out.println("Cleanup after test");
    }
}

// Test class uses @ExtendWith(MyExtension.class) and has one test method that prints "Running test"
ASetup before test\nRunning test\nCleanup after test
BCleanup after test\nSetup before test\nRunning test
CSetup before test\nCleanup after test\nRunning test
DRunning test\nSetup before test\nCleanup after test
Attempts:
2 left
💡 Hint
Remember the order: beforeEach runs before the test, afterEach runs after.
🔧 Debug
advanced
2:00remaining
Identify the error in this AfterEachCallback implementation
What error will occur when running this JUnit 5 extension code implementing AfterEachCallback?
JUnit
import org.junit.jupiter.api.extension.*;

public class FaultyExtension implements AfterEachCallback {
    @Override
    public void afterEach() {
        System.out.println("Cleaning up");
    }
}
ANo error, code runs fine
BRuntime NullPointerException
CCompilation error: method afterEach() does not override or implement a method from a supertype
DTest fails with IllegalStateException
Attempts:
2 left
💡 Hint
Check the method signature required by AfterEachCallback interface.
❓ framework
expert
2:30remaining
Correct usage of BeforeEachCallback and AfterEachCallback in a JUnit 5 extension
Which code snippet correctly implements both BeforeEachCallback and AfterEachCallback interfaces in a JUnit 5 extension to print messages before and after each test method?
A
public class Ext implements BeforeEachCallback, AfterEachCallback {
    public void beforeEach() {
        System.out.println("Before");
    }
    public void afterEach() {
        System.out.println("After");
    }
}
B
public class Ext implements BeforeEachCallback, AfterEachCallback {
    @Override
    public void beforeEach(ExtensionContext context) {
        System.out.println("Before");
    }
    @Override
    public void afterEach(ExtensionContext context) {
        System.out.println("After");
    }
}
C
public class Ext implements BeforeEachCallback, AfterEachCallback {
    @Override
    public void beforeEach() {
        System.out.println("Before");
    }
    @Override
    public void afterEach() {
        System.out.println("After");
    }
}
D
public class Ext implements BeforeEachCallback, AfterEachCallback {
    public void beforeEach(ExtensionContext context) {
        System.out.println("Before");
    }
    public void afterEach(ExtensionContext context) {
        System.out.println("After");
    }
}
Attempts:
2 left
💡 Hint
Check method signatures and use of @Override annotations.

Practice

(1/5)
1. What is the main purpose of implementing BeforeEachCallback and AfterEachCallback in JUnit 5?
easy
A. To skip tests based on conditions
B. To run code before and after each test method for setup and cleanup
C. To replace the test methods with custom logic
D. To run code only once before all tests in a class

Solution

  1. Step 1: Understand the role of BeforeEachCallback and AfterEachCallback

    These interfaces allow running code before and after each test method, typically for setup and cleanup.
  2. Step 2: Compare with other lifecycle callbacks

    Unlike @BeforeAll or @AfterAll, these run before and after every test, not once per class.
  3. Final Answer:

    To run code before and after each test method for setup and cleanup -> Option B
  4. Quick Check:

    BeforeEachCallback and AfterEachCallback = setup and cleanup per test [OK]
Hint: They run code before and after each test method [OK]
Common Mistakes:
  • Confusing with @BeforeAll/@AfterAll which run once per class
  • Thinking they replace test methods
  • Assuming they skip tests
2. Which method must be implemented when using the BeforeEachCallback interface in JUnit 5?
easy
A. void beforeEach(ExtensionContext context)
B. void beforeAll(ExtensionContext context)
C. void afterEach(ExtensionContext context)
D. void afterAll(ExtensionContext context)

Solution

  1. Step 1: Recall the method signature for BeforeEachCallback

    The interface requires implementing beforeEach(ExtensionContext context) to run code before each test.
  2. Step 2: Differentiate from other lifecycle methods

    Methods like beforeAll or afterAll belong to other interfaces or annotations, not BeforeEachCallback.
  3. Final Answer:

    void beforeEach(ExtensionContext context) -> Option A
  4. Quick Check:

    BeforeEachCallback method = beforeEach() [OK]
Hint: BeforeEachCallback requires beforeEach() method [OK]
Common Mistakes:
  • Using beforeAll or afterAll methods incorrectly
  • Confusing AfterEachCallback method with BeforeEachCallback
  • Missing the ExtensionContext parameter
3. Given the following JUnit 5 extension code, what will be printed when running a test method?
public class MyExtension implements BeforeEachCallback, AfterEachCallback {
    @Override
    public void beforeEach(ExtensionContext context) {
        System.out.println("Start " + context.getDisplayName());
    }
    @Override
    public void afterEach(ExtensionContext context) {
        System.out.println("End " + context.getDisplayName());
    }
}

Assuming the test method is named testExample() in class ExampleTest.
medium
A. Start ExampleTest testExample End
B. Only Start testExample(ExampleTest) is printed
C. testExample Start ExampleTest End
D. Start testExample(ExampleTest) End testExample(ExampleTest)

Solution

  1. Step 1: Understand what context.getDisplayName() returns

    It returns the display name of the current test, typically in the format "methodName(className)".
  2. Step 2: Analyze the print statements in beforeEach and afterEach

    Before the test, it prints "Start " plus the display name; after the test, it prints "End " plus the same display name.
  3. Final Answer:

    Start testExample(ExampleTest) End testExample(ExampleTest) -> Option D
  4. Quick Check:

    beforeEach prints Start + displayName, afterEach prints End + displayName [OK]
Hint: context.getDisplayName() shows method and class name [OK]
Common Mistakes:
  • Assuming displayName returns only class or method name
  • Thinking only one print runs
  • Mixing order of prints
4. Identify the error in this JUnit 5 extension code implementing AfterEachCallback:
public class CleanupExtension implements AfterEachCallback {
    public void afterEach() {
        System.out.println("Cleaning up after test");
    }
}
medium
A. Class must implement BeforeEachCallback too
B. afterEach method should be static
C. Missing ExtensionContext parameter in afterEach method
D. System.out.println is not allowed in extensions

Solution

  1. Step 1: Check method signature for AfterEachCallback

    The interface requires implementing afterEach(ExtensionContext context) with the ExtensionContext parameter.
  2. Step 2: Identify the missing parameter error

    The code's afterEach method has no parameters, so it does not correctly override the interface method.
  3. Final Answer:

    Missing ExtensionContext parameter in afterEach method -> Option C
  4. Quick Check:

    AfterEachCallback.afterEach() requires ExtensionContext parameter [OK]
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

  1. 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.
  2. 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.
  3. Final Answer:

    Store start time in a field in beforeEach, then calculate elapsed time in afterEach using the same field -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard