1 21 package db4ounit; 22 23 import java.lang.reflect.InvocationTargetException ; 24 import java.lang.reflect.Method ; 25 26 29 public class TestMethod implements Test { 30 31 public interface LabelProvider { 32 String getLabel(TestMethod method); 33 } 34 35 public static LabelProvider DEFAULT_LABEL_PROVIDER = new LabelProvider() { 36 public String getLabel(TestMethod method) { 37 return method.getSubject().getClass().getName() + "." + method.getMethod().getName(); 38 } 39 }; 40 41 private final Object _subject; 42 private final Method _method; 43 private final LabelProvider _labelProvider; 44 45 public TestMethod(Object instance, Method method) { 46 this(instance, method, DEFAULT_LABEL_PROVIDER); 47 } 48 49 public TestMethod(Object instance, Method method, LabelProvider labelProvider) { 50 if (null == instance) throw new IllegalArgumentException ("instance"); 51 if (null == method) throw new IllegalArgumentException ("method"); 52 if (null == labelProvider) throw new IllegalArgumentException ("labelProvider"); 53 _subject = instance; 54 _method = method; 55 _labelProvider = labelProvider; 56 } 57 58 public Object getSubject() { 59 return _subject; 60 } 61 62 public Method getMethod() { 63 return _method; 64 } 65 66 public String getLabel() { 67 return _labelProvider.getLabel(this); 68 } 69 70 public void run(TestResult result) { 71 try { 72 result.testStarted(this); 73 setUp(); 74 invoke(); 75 } catch (InvocationTargetException e) { 76 result.testFailed(this, e.getTargetException()); 77 } catch (Exception e) { 78 result.testFailed(this, e); 79 } finally { 80 try { 81 tearDown(); 82 } catch (TestException e) { 83 result.testFailed(this, e); 84 } 85 } 86 } 87 88 protected void invoke() throws Exception { 89 _method.invoke(_subject, new Object [0]); 90 } 91 92 protected void tearDown() { 93 if (_subject instanceof TestLifeCycle) { 94 try { 95 ((TestLifeCycle)_subject).tearDown(); 96 } catch (Exception e) { 97 throw new TearDownFailureException(e); 98 } 99 } 100 } 101 102 protected void setUp() { 103 if (_subject instanceof TestLifeCycle) { 104 try { 105 ((TestLifeCycle)_subject).setUp(); 106 } catch (Exception e) { 107 throw new SetupFailureException(e); 108 } 109 } 110 } 111 } 112 | Popular Tags |