1 package org.junit.rules; 2 3 import org.junit.internal.AssumptionViolatedException; 4 import org.junit.runner.Description; 5 import org.junit.runners.model.Statement; 6 7 /** 8 * TestWatcher is a base class for Rules that take note of the testing 9 * action, without modifying it. For example, this class will keep a log of each 10 * passing and failing test: 11 * 12 * <pre> 13 * public static class WatchmanTest { 14 * private static String watchedLog; 15 * 16 * @Rule 17 * public MethodRule watchman= new TestWatcher() { 18 * @Override 19 * protected void failed(Description d) { 20 * watchedLog+= d + "\n"; 21 * } 22 * 23 * @Override 24 * protected void succeeded(Description d) { 25 * watchedLog+= d + " " + "success!\n"; 26 * } 27 * }; 28 * 29 * @Test 30 * public void fails() { 31 * fail(); 32 * } 33 * 34 * @Test 35 * public void succeeds() { 36 * } 37 * } 38 * </pre> 39 */ 40 public abstract class TestWatcher implements TestRule { apply(final Statement base, final Description description)41 public Statement apply(final Statement base, final Description description) { 42 return new Statement() { 43 @Override 44 public void evaluate() throws Throwable { 45 starting(description); 46 try { 47 base.evaluate(); 48 succeeded(description); 49 } catch (AssumptionViolatedException e) { 50 throw e; 51 } catch (Throwable t) { 52 failed(t, description); 53 throw t; 54 } finally { 55 finished(description); 56 } 57 } 58 }; 59 } 60 61 /** 62 * Invoked when a test succeeds 63 * 64 * @param description 65 */ 66 protected void succeeded(Description description) { 67 } 68 69 /** 70 * Invoked when a test fails 71 * 72 * @param e 73 * @param description 74 */ 75 protected void failed(Throwable e, Description description) { 76 } 77 78 /** 79 * Invoked when a test is about to start 80 * 81 * @param description 82 */ 83 protected void starting(Description description) { 84 } 85 86 87 /** 88 * Invoked when a test method finishes (whether passing or failing) 89 * 90 * @param description 91 */ 92 protected void finished(Description description) { 93 } 94 } 95