1 7 package com.tirsen.nanning; 8 9 import java.lang.reflect.Method ; 10 11 import junit.framework.Assert; 12 13 21 public class MockInterceptor implements MethodInterceptor { 22 private Object expectTarget; 23 private Object actualTarget; 24 private Object expectProxy; 25 private Object actualProxy; 26 private Method expectMethod; 27 private int expectCalledTimes = -1; 28 private int calledTimes; 29 private int expectAtIndex = -1; 30 private int actualAtIndex; 31 private int expectNumberOfInterceptors = -1; 32 private int actualNumberOfInterceptors; 33 34 public MockInterceptor() { 35 } 36 37 public void verify() { 38 Assert.assertTrue("was never called", calledTimes != 0); 39 if (expectCalledTimes != -1) { 40 Assert.assertEquals("was not called correct number of times", expectCalledTimes, calledTimes); 41 } 42 if (expectProxy != null) { 43 Assert.assertSame("expectProxy was not correct during call", expectProxy, actualProxy); 44 } 45 46 expectCalledTimes = -1; 48 expectAtIndex = -1; 49 expectMethod = null; 50 expectNumberOfInterceptors = -1; 51 expectProxy = null; 52 expectTarget = null; 53 } 54 55 public Object invoke(Invocation invocation) throws Throwable { 56 calledTimes++; 57 actualTarget = invocation.getTarget(); 58 actualProxy = invocation.getProxy(); 59 60 actualAtIndex = invocation.getCurrentIndex(); 61 62 Assert.assertSame(this, invocation.getInterceptor(invocation.getCurrentIndex())); 63 64 actualNumberOfInterceptors = invocation.getNumberOfInterceptors(); 66 invocation.getInterceptor(actualNumberOfInterceptors - 1); try { 68 invocation.getInterceptor(actualNumberOfInterceptors); Assert.fail("Invocation.getNumberOfInterceptors doesn't work."); 71 } catch (Exception shouldHappen) { 73 } 74 75 if (expectTarget != null) { 76 Assert.assertSame("real object was not correct during mixinCall", expectTarget, actualTarget); 77 } 78 if (expectMethod != null) { 79 Assert.assertEquals(expectMethod, invocation.getMethod()); 80 } 81 82 Assert.assertNull(invocation.getArgs()); 83 84 if (expectAtIndex != -1) { 85 Assert.assertEquals("interceptor not at correct index during call", 86 expectAtIndex, actualAtIndex); 87 } 88 if (expectNumberOfInterceptors != -1) { 89 Assert.assertEquals("number of interceptor not at correct index during call", 90 expectNumberOfInterceptors, actualNumberOfInterceptors); 91 } 92 93 return invocation.invokeNext(); 94 } 95 96 public void expectTarget(Object o) { 97 expectTarget = o; 98 } 99 100 public void expectMethod(Method expectMethod) { 101 this.expectMethod = expectMethod; 102 } 103 104 public void expectProxy(Object proxy) { 105 this.expectProxy = proxy; 106 } 107 108 public void expectCalledTimes(int i) { 109 this.expectCalledTimes = i; 110 } 111 112 116 public void expectAtIndex(int index) { 117 this.expectAtIndex = index; 118 } 119 120 public void expectNumberOfInterceptors(int index) { 121 this.expectNumberOfInterceptors = index; 122 } 123 } 124 | Popular Tags |