1 package org.junit.internal.runners; 2 3 import java.lang.annotation.Annotation ; 4 import java.lang.reflect.InvocationTargetException ; 5 import java.lang.reflect.Method ; 6 import java.util.List ; 7 8 public abstract class BeforeAndAfterRunner { 9 private static class FailedBefore extends Exception { 10 private static final long serialVersionUID= 1L; 11 } 12 13 private final Class <? extends Annotation > fBeforeAnnotation; 14 15 private final Class <? extends Annotation > fAfterAnnotation; 16 17 private TestIntrospector fTestIntrospector; 18 19 private Object fTest; 20 21 public BeforeAndAfterRunner(Class <?> testClass, 22 Class <? extends Annotation > beforeAnnotation, 23 Class <? extends Annotation > afterAnnotation, 24 Object 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 targetException); 44 45 private void runBefores() throws FailedBefore { 47 try { 48 List <Method > befores= fTestIntrospector.getTestMethods(fBeforeAnnotation); 49 for (Method before : befores) 50 invokeMethod(before); 51 } catch (InvocationTargetException e) { 52 addFailure(e.getTargetException()); 53 throw new FailedBefore(); 54 } catch (Throwable e) { 55 addFailure(e); 56 throw new FailedBefore(); 57 } 58 } 59 60 private void runAfters() { 62 List <Method > afters= fTestIntrospector.getTestMethods(fAfterAnnotation); 63 for (Method after : afters) 64 try { 65 invokeMethod(after); 66 } catch (InvocationTargetException e) { 67 addFailure(e.getTargetException()); 68 } catch (Throwable e) { 69 addFailure(e); } 71 } 72 73 private void invokeMethod(Method method) throws Exception { 74 method.invoke(fTest); 75 } 76 } 77 | Popular Tags |