0
0
JUnittesting~5 mins

TestWatcher for reporting in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is TestWatcher in JUnit?
TestWatcher is a JUnit extension that allows you to add custom behavior when tests succeed, fail, or are skipped. It helps in reporting and logging test results.
Click to reveal answer
beginner
How do you use TestWatcher to log a message when a test fails?
Override the <code>failed(Throwable e, Description description)</code> method in a TestWatcher subclass to add custom logging or reporting when a test fails.
Click to reveal answer
beginner
Which method in TestWatcher is called when a test succeeds?
The succeeded(Description description) method is called when a test passes successfully.
Click to reveal answer
intermediate
Why use TestWatcher instead of @After or @Before methods for reporting?
TestWatcher provides hooks specifically for test result events (success, failure, skip), making it easier and cleaner to add reporting logic tied directly to test outcomes.
Click to reveal answer
intermediate
Show a simple example of a TestWatcher that prints test start and finish messages.
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class MyTestWatcher extends TestWatcher {
  @Override
  protected void starting(Description description) {
    System.out.println("Starting: " + description.getMethodName());
  }
  @Override
  protected void finished(Description description) {
    System.out.println("Finished: " + description.getMethodName());
  }
}
Click to reveal answer
Which TestWatcher method is called when a test fails?
Asucceeded(Description description)
Bfinished(Description description)
Cstarting(Description description)
Dfailed(Throwable e, Description description)
What is the main purpose of using TestWatcher in JUnit?
ATo add custom behavior on test lifecycle events
BTo write test assertions
CTo configure test timeouts
DTo create test data
Which method would you override to log when a test starts?
Astarting(Description description)
Bfailed(Throwable e, Description description)
Csucceeded(Description description)
Dfinished(Description description)
Can TestWatcher be used to skip tests?
AOnly for parameterized tests
BNo, it only observes test events
COnly if combined with @Ignore
DYes, it can skip tests
Which JUnit version introduced TestWatcher as an extension?
AJUnit 5
BJUnit 3
CJUnit 4
DJUnit 6
Explain how TestWatcher helps improve test reporting in JUnit.
Think about how you can react to test outcomes automatically.
You got /4 concepts.
    Describe how to implement a TestWatcher that logs test start and failure events.
    Focus on which methods to override and what to log.
    You got /4 concepts.