Challenge - 5 Problems
TestWatcher Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this TestWatcher override?
Consider this JUnit 5 TestWatcher extension code. What will be printed when the test fails?
JUnit
import org.junit.jupiter.api.extension.TestWatcher; import org.junit.jupiter.api.extension.ExtensionContext; public class MyWatcher implements TestWatcher { @Override public void testFailed(ExtensionContext context, Throwable cause) { System.out.println("Test failed: " + context.getDisplayName()); } } // Assume this watcher is registered for a test named "exampleTest" which fails.
Attempts:
2 left
💡 Hint
The testFailed method prints the test name on failure.
✗ Incorrect
The testFailed method is called on test failure and prints the display name of the test, which is 'exampleTest'.
❓ assertion
intermediate2:00remaining
Which assertion correctly verifies a test was skipped using TestWatcher?
You want to assert inside a TestWatcher that a test was skipped. Which assertion is correct?
JUnit
import org.junit.jupiter.api.extension.TestWatcher; import org.junit.jupiter.api.extension.ExtensionContext; import java.util.Optional; public class SkipWatcher implements TestWatcher { @Override public void testSkipped(ExtensionContext context, Optional<String> reason) { // Which assertion below is correct? } }
Attempts:
2 left
💡 Hint
The reason parameter is Optional and should be present if skipped.
✗ Incorrect
The reason parameter is an Optional containing the skip reason. It should be present when a test is skipped.
🔧 Debug
advanced2:00remaining
Why does this TestWatcher not print on test success?
This TestWatcher override does not print anything when a test passes. Why?
public class SilentWatcher implements TestWatcher {
@Override
public void testSuccessful(ExtensionContext context) {
// Intentionally left blank
}
}
Attempts:
2 left
💡 Hint
Check what the method implementation does.
✗ Incorrect
The testSuccessful method is called on success but since it is empty, no output occurs.
🧠 Conceptual
advanced2:00remaining
What is the main purpose of TestWatcher in JUnit 5?
Choose the best description of what TestWatcher is used for in JUnit 5 testing.
Attempts:
2 left
💡 Hint
Think about what events TestWatcher listens to.
✗ Incorrect
TestWatcher listens to test lifecycle events like success, failure, and skip to allow custom reporting or actions.
❓ framework
expert2:00remaining
How to register a TestWatcher extension for all tests in a class?
You want to apply a TestWatcher implementation to all tests in a JUnit 5 test class. Which is the correct way?
Attempts:
2 left
💡 Hint
JUnit 5 uses annotations to register extensions.
✗ Incorrect
The @ExtendWith annotation registers the TestWatcher extension for all tests in the class.