diff options
Diffstat (limited to 'junit4/src/main/java/org/junit/rules/TestWatcher.java')
-rw-r--r-- | junit4/src/main/java/org/junit/rules/TestWatcher.java | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/junit4/src/main/java/org/junit/rules/TestWatcher.java b/junit4/src/main/java/org/junit/rules/TestWatcher.java new file mode 100644 index 0000000..351b449 --- /dev/null +++ b/junit4/src/main/java/org/junit/rules/TestWatcher.java @@ -0,0 +1,94 @@ +package org.junit.rules; + +import org.junit.internal.AssumptionViolatedException; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * TestWatcher is a base class for Rules that take note of the testing + * action, without modifying it. For example, this class will keep a log of each + * passing and failing test: + * + * <pre> + * public static class WatchmanTest { + * private static String watchedLog; + * + * @Rule + * public MethodRule watchman= new TestWatcher() { + * @Override + * protected void failed(Description d) { + * watchedLog+= d + "\n"; + * } + * + * @Override + * protected void succeeded(Description d) { + * watchedLog+= d + " " + "success!\n"; + * } + * }; + * + * @Test + * public void fails() { + * fail(); + * } + * + * @Test + * public void succeeds() { + * } + * } + * </pre> + */ +public abstract class TestWatcher implements TestRule { + public Statement apply(final Statement base, final Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + starting(description); + try { + base.evaluate(); + succeeded(description); + } catch (AssumptionViolatedException e) { + throw e; + } catch (Throwable t) { + failed(t, description); + throw t; + } finally { + finished(description); + } + } + }; + } + + /** + * Invoked when a test succeeds + * + * @param description + */ + protected void succeeded(Description description) { + } + + /** + * Invoked when a test fails + * + * @param e + * @param description + */ + protected void failed(Throwable e, Description description) { + } + + /** + * Invoked when a test is about to start + * + * @param description + */ + protected void starting(Description description) { + } + + + /** + * Invoked when a test method finishes (whether passing or failing) + * + * @param description + */ + protected void finished(Description description) { + } +} |