1 /* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.dx.mockito; 18 19 import com.android.dx.stock.ProxyBuilder; 20 21 import org.mockito.Mockito; 22 import org.mockito.invocation.InvocationFactory.RealMethodBehavior; 23 import org.mockito.invocation.MockHandler; 24 25 import java.lang.reflect.InvocationHandler; 26 import java.lang.reflect.Method; 27 28 import static org.mockito.Mockito.withSettings; 29 30 /** 31 * Handles proxy method invocations to dexmaker's InvocationHandler by calling 32 * a MockitoInvocationHandler. 33 */ 34 final class InvocationHandlerAdapter implements InvocationHandler { 35 private MockHandler handler; 36 InvocationHandlerAdapter(MockHandler handler)37 public InvocationHandlerAdapter(MockHandler handler) { 38 this.handler = handler; 39 } 40 41 @Override invoke(final Object proxy, final Method method, final Object[] rawArgs)42 public Object invoke(final Object proxy, final Method method, final Object[] rawArgs) 43 throws Throwable { 44 // args can be null if the method invoked has no arguments, but Mockito expects a non-null array 45 Object[] args = rawArgs != null ? rawArgs : new Object[0]; 46 if (isEqualsMethod(method)) { 47 return proxy == args[0]; 48 } else if (isHashCodeMethod(method)) { 49 return System.identityHashCode(proxy); 50 } 51 52 return handler.handle(Mockito.framework().getInvocationFactory().createInvocation(proxy, 53 withSettings().build(proxy.getClass().getSuperclass()), method, 54 new RealMethodBehavior() { 55 @Override 56 public Object call() throws Throwable { 57 return ProxyBuilder.callSuper(proxy, method, rawArgs); 58 } 59 }, args)); 60 } 61 62 public MockHandler getHandler() { 63 return handler; 64 } 65 66 public void setHandler(MockHandler handler) { 67 this.handler = handler; 68 } 69 70 private static boolean isEqualsMethod(Method method) { 71 return method.getName().equals("equals") 72 && method.getParameterTypes().length == 1 73 && method.getParameterTypes()[0] == Object.class; 74 } 75 76 private static boolean isHashCodeMethod(Method method) { 77 return method.getName().equals("hashCode") 78 && method.getParameterTypes().length == 0; 79 } 80 } 81