1
2
3
4 package himock.core;
5
6 import junit.framework.Assert;
7 import himock.core.exception.CannotMockInnerOrAnonymousClassException;
8 import himock.core.exception.MockedClassNeedDefaultConstructorException;
9 import himock.util.ClassUtil;
10 import net.sf.cglib.proxy.Enhancer;
11 import net.sf.cglib.proxy.MethodInterceptor;
12 import net.sf.cglib.proxy.MethodProxy;
13
14 /***
15 * @author Chen Peng ,chen56@msn.com
16 */
17 public class ClassMockObjectMaker implements IMockObjectMaker{
18 private final MockBehavior fMockInvocationer;
19 public ClassMockObjectMaker(MockBehavior mockInvocationer) {
20 Class c = mockInvocationer.fMockedType;
21
22 Assert.assertFalse(c.isInterface());
23
24 if(ClassUtil.isInnerOrAnonymous(c)){
25 throw new CannotMockInnerOrAnonymousClassException(c);
26 }
27
28
29
30 if(!ClassUtil.isOuterClassHasDefaultConstructor(c))
31 throw new MockedClassNeedDefaultConstructorException(c);
32
33 this.fMockInvocationer=mockInvocationer;
34 }
35
36 public Object mock() {
37 return Enhancer.create(fMockInvocationer.fMockedType, new MethodInterceptorImpl());
38 }
39 private class MethodInterceptorImpl implements MethodInterceptor {
40 public Object intercept(Object obj, java.lang.reflect.Method method,
41 Object[] args, MethodProxy proxy) throws Throwable{
42 return fMockInvocationer.invoke(method, args);
43 }
44 }
45 }
46