1
2
3
4 package himock.core;
5
6 import himock.core.exception.ExpertedInvocationException;
7 import himock.core.exception.MethodReturnTypeMismatchException;
8 import himock.core.exception.NotImplementedMethodException;
9 import himock.util.ClassUtil;
10
11 import java.lang.reflect.Method;
12 import java.util.HashSet;
13 import java.util.Set;
14 import java.util.Arrays;
15 /***
16 * @author Chen Peng ,chen56@msn.com
17 */
18 public class MockBehavior {
19 Class fMockedType;
20 private Object fMocker;
21 private Set fExpertedMethodInvocationsOfMocker;
22
23 public MockBehavior(Class mockedType, Object mocker){
24 this.fMockedType=mockedType;
25 this.fMocker=mocker;
26 fExpertedMethodInvocationsOfMocker = new HashSet(Arrays.asList(mocker.getClass().getDeclaredMethods()));
27 }
28 public Object invoke(Method mockedMethod,Object[] args) throws Throwable{
29 checkMethodDefineOfMocker(mockedMethod);
30
31 Method methodOfMocker = ClassUtil.getSameSignaturegetDeclaredMethod(fMocker.getClass(),mockedMethod);
32 methodOfMocker.setAccessible(true);
33 Object result = methodOfMocker.invoke(fMocker, args);
34 fExpertedMethodInvocationsOfMocker.remove(methodOfMocker);
35 return result;
36 }
37 private void checkMethodDefineOfMocker(Method mockedMethod) throws NotImplementedMethodException {
38 if(!ClassUtil.isContainsThisSignatureDeclaredMethod(fMocker.getClass(),mockedMethod))
39 throw new NotImplementedMethodException(mockedMethod);
40 Method mv = ClassUtil.getSameSignaturegetDeclaredMethod(fMocker.getClass(),mockedMethod);
41 if(!mv.getReturnType().equals(mockedMethod.getReturnType() ))
42 throw new MethodReturnTypeMismatchException(mockedMethod,mv );
43 }
44
45 public void verify() {
46 if(!fExpertedMethodInvocationsOfMocker.isEmpty())
47 throw new ExpertedInvocationException((Method[])fExpertedMethodInvocationsOfMocker.toArray(new Method[0]));
48 }
49 }