KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > junit > internal > runners > BeforeAndAfterRunner


1 package org.junit.internal.runners;
2
3 import java.lang.annotation.Annotation JavaDoc;
4 import java.lang.reflect.InvocationTargetException JavaDoc;
5 import java.lang.reflect.Method JavaDoc;
6 import java.util.List JavaDoc;
7
8 public abstract class BeforeAndAfterRunner {
9     private static class FailedBefore extends Exception JavaDoc {
10         private static final long serialVersionUID= 1L;
11     }
12
13     private final Class JavaDoc<? extends Annotation JavaDoc> fBeforeAnnotation;
14
15     private final Class JavaDoc<? extends Annotation JavaDoc> fAfterAnnotation;
16
17     private TestIntrospector fTestIntrospector;
18
19     private Object JavaDoc fTest;
20
21     public BeforeAndAfterRunner(Class JavaDoc<?> testClass,
22             Class JavaDoc<? extends Annotation JavaDoc> beforeAnnotation,
23             Class JavaDoc<? extends Annotation JavaDoc> afterAnnotation,
24             Object JavaDoc test) {
25         fBeforeAnnotation= beforeAnnotation;
26         fAfterAnnotation= afterAnnotation;
27         fTestIntrospector= new TestIntrospector(testClass);
28         fTest= test;
29     }
30
31     public void runProtected() {
32         try {
33             runBefores();
34             runUnprotected();
35         } catch (FailedBefore e) {
36         } finally {
37             runAfters();
38         }
39     }
40
41     protected abstract void runUnprotected();
42
43     protected abstract void addFailure(Throwable JavaDoc targetException);
44
45     // Stop after first failed @Before
46
private void runBefores() throws FailedBefore {
47         try {
48             List JavaDoc<Method JavaDoc> befores= fTestIntrospector.getTestMethods(fBeforeAnnotation);
49             for (Method JavaDoc before : befores)
50                 invokeMethod(before);
51         } catch (InvocationTargetException JavaDoc e) {
52             addFailure(e.getTargetException());
53             throw new FailedBefore();
54         } catch (Throwable JavaDoc e) {
55             addFailure(e);
56             throw new FailedBefore();
57         }
58     }
59
60     // Try to run all @Afters regardless
61
private void runAfters() {
62         List JavaDoc<Method JavaDoc> afters= fTestIntrospector.getTestMethods(fAfterAnnotation);
63         for (Method JavaDoc after : afters)
64             try {
65                 invokeMethod(after);
66             } catch (InvocationTargetException JavaDoc e) {
67                 addFailure(e.getTargetException());
68             } catch (Throwable JavaDoc e) {
69                 addFailure(e); // Untested, but seems impossible
70
}
71     }
72     
73     private void invokeMethod(Method JavaDoc method) throws Exception JavaDoc {
74         method.invoke(fTest);
75     }
76 }
77
Popular Tags