1 /**
2 * Copyright 2010 The Kuali Foundation Licensed under the
3 * Educational Community License, Version 2.0 (the "License"); you may
4 * not use this file except in compliance with the License. You may
5 * obtain a copy of the License at
6 *
7 * http://www.osedu.org/licenses/ECL-2.0
8 *
9 * Unless required by applicable law or agreed to in writing,
10 * software distributed under the License is distributed on an "AS IS"
11 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12 * or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15
16 package org.kuali.student.common.test.mock;
17
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Proxy;
21 import java.util.HashMap;
22 import java.util.Map;
23
24 /**
25 * @author Daniel Epstein
26 *
27 */
28 public class MockProxy implements InvocationHandler {
29 private Map<String,Object> methodReturnMap;
30
31 /**
32 * Creates a new instance of an object that implements the interface you pass it.
33 * The Map contains a map of method names to return values.
34 * If a method is not in the map, then invoking that method will return null
35 * Example:
36 * Map<String,Object> methodReturnMap = new HashMap<String,Object>();
37 * MyInterface myObject = MockProxy.newInstance(map, MyInterface.class);
38 * map.put("foo", "NEW RETRUN VALUE");
39 * System.out.println(myObject.foo()); // Outputs "NEW RETRUN VALUE"
40 *
41 * @param <T>
42 * @param methodReturnMap
43 * @param interfaceClass
44 * @return
45 * @throws InstantiationException
46 * @throws IllegalAccessException
47 */
48 @SuppressWarnings("unchecked")
49 public static <T> T newInstance(Map<String,Object> methodReturnMap, Class<T> interfaceClass) throws InstantiationException, IllegalAccessException {
50 return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, new MockProxy(methodReturnMap));
51 }
52
53 private MockProxy(Map<String,Object> methodReturnMap) {
54 super();
55 this.methodReturnMap = methodReturnMap;
56 //Create the map if it does not exist
57 if(this.methodReturnMap==null){
58 this.methodReturnMap = new HashMap<String, Object>();
59 }
60 }
61
62 public MockProxy() {
63 super();
64 }
65
66 /* (non-Javadoc)
67 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
68 */
69 @Override
70 public Object invoke(Object proxy, Method method, Object[] args)
71 throws Throwable {
72 Object result = methodReturnMap.get(method.getName());
73
74 if (result instanceof MockArgumentMapper){
75 result = ((MockArgumentMapper)result).getReturnValue(args);
76 }
77
78 return result;
79 }
80
81 }