Home | History | Annotate | Download | only in littlemock
      1 /*
      2  * Copyright 2011 Google Inc.
      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.google.testing.littlemock;
     18 
     19 import java.io.File;
     20 import java.io.ObjectInputStream;
     21 import java.io.ObjectStreamClass;
     22 import java.lang.reflect.Field;
     23 import java.lang.reflect.InvocationHandler;
     24 import java.lang.reflect.Method;
     25 import java.lang.reflect.Proxy;
     26 import java.util.ArrayList;
     27 import java.util.Arrays;
     28 import java.util.HashMap;
     29 import java.util.List;
     30 import java.util.Map;
     31 import java.util.concurrent.Callable;
     32 import java.util.concurrent.CopyOnWriteArrayList;
     33 import java.util.concurrent.atomic.AtomicLong;
     34 import java.util.concurrent.atomic.AtomicReference;
     35 
     36 /**
     37  * Very lightweight and simple mocking framework, inspired by Mockito, http://mockito.org.
     38  *
     39  * <p>It supports only a <b>small subset</b> of the APIs provided by Mockito and other mocking
     40  * frameworks.
     41  *
     42  * <p>This project was originally designed to be lightweight and suitable for platforms that don't
     43  * support dynamic class generation, for example Android.  Since the release of the open
     44  * source dexmaker project http://code.google.com/p/dexmaker/ we can now mock concrete classes
     45  * too.
     46  *
     47  * <p>Here is an example of how to use the framework.
     48  *
     49  * <p>Suppose that we have this interface:
     50  * <pre>
     51  *     public interface Foo {
     52  *       public String aString(int input);
     53  *       public void doSomething();
     54  *     }
     55  * </pre>
     56  *
     57  * <p>Then stubbing out mocks works as follows:
     58  * <pre>
     59  *     Foo mockFoo = mock(Foo.class);  // Create the mock.
     60  *     doReturn("hello").when(mockFoo).aString(anyInt());  // Stub the mock to return "hello".
     61  *     doThrow(new IOException("oh noes")).when(mockFoo).doSomething();
     62  *     assertEquals("hello", mockFoo.aString(5));  // Use the mock - performs as expected.
     63  *     mockFoo.doSomething();  // This will throw an IOException.
     64  * </pre>
     65  *
     66  * <p>You can verify in the 'natural place', after the method call has happened, like this:
     67  * <pre>
     68  *     Foo mockFoo = mock(Foo.class);
     69  *     assertEquals(null, mockFoo.aString(6));  // Unstubbed method calls return a sensible default.
     70  *     verify(mockFoo).aString(6);  // This will pass, aString() was called once.
     71  *     verify(mockFoo, never()).doSomething();  // This will pass, doSomething was never called.
     72  *     verify(mockFoo, times(3)).aString(anyInt());  // This will fail, was called once only.
     73  * </pre>
     74  *
     75  * <p>The documentation is still incomplete.  You can look at the {@link LittleMockTest} class and
     76  * its unit tests - since they tell you exactly what operations are supported and how to use them.
     77  *
     78  * <p>The reasons I much prefer Mockito's approach to the one of EasyMock are as follows:
     79  * <ul>
     80  *   <li>No need to remember to put your mocks in replay mode.</li>
     81  *   <li>No need to remember to call verify, a dangerous source of false-positive tests or
     82  *   alternatively over-specified tests.</li>
     83  *   <li>Much less over-specification: only verify what you actually care about.</li>
     84  *   <li>Which in turn leads to better separated tests, each test verifying only a part of the
     85  *   desired behaviour.</li>
     86  *   <li>Which also leads to less fragile tests, where adding another method call on your
     87  *   dependencies doesn't break unrelated tests.</li>
     88  *   <li>Simpler sharing of common setup method with specific tests overridding individual
     89  *   behavious however they want to, only the most recent stubbed call is the one that counts.</li>
     90  *   <li>More natural order for tests: set up stubs, execute tests, verify that it worked.</li>
     91  *   <li>More unified syntax that doesn't require special case for differences between void method
     92  *   calls and method calls that return a value.</li>
     93  * </ul>
     94  *
     95  * <p>There were enough reasons that I wanted to give Mockito a try.  It didn't work on Android
     96  * because of issues with class generation.  So I looked at the documentation and examples page and
     97  * added tests for all the examples, and then implemented the this framework.  I should stress that
     98  * this is a clean-room implementation, and as such it's possible that there are a couple of methods
     99  * that don't work in the same way as Mockito's implementation.  Where that is the case I think we
    100  * should fix once we discover them.  There is also some functionality missing, but it will be added
    101  * in due course.
    102  *
    103  * <p>Over time, the API has diverged slightly from the one of Mockito, as I have added APIs that I
    104  * found convenient but that did not have an equivalent in Mockite itself.  For anything that has an
    105  * equivalent in Mockito I tried to keep the same name and syntax, to make it easier to transition
    106  * between using one framework to using the other, e.g., when developing both an Android application
    107  * using this framework and a desktop application using Mockito.
    108  *
    109  * @author hugohudson (at) gmail.com (Hugo Hudson)
    110  */
    111 /*@NotThreadSafe*/
    112 public class LittleMock {
    113   /** Generates a {@link Behaviour} suitable for void methods. */
    114   public static Behaviour doNothing() { return doReturn(null); }
    115 
    116   /** Generates a {@link Behaviour} that returns the given result. */
    117   public static <T> Behaviour doReturn(final T result) {
    118     return new BehaviourImpl(new Action() {
    119       @Override public T doAction(Method method, Object[] args) { return result; }
    120       @Override public Class<?> getReturnType() {
    121         return (result == null) ? null : result.getClass();
    122       }
    123     });
    124   }
    125 
    126   /**
    127    * Gets a {@link Behaviour} that will execute the given {@link Callable} and return its result.
    128    */
    129   public static <T> Behaviour doAnswer(final Callable<T> callable) {
    130     return new BehaviourImpl(new Action() {
    131       @Override
    132       public T doAction(Method method, Object[] args) throws Throwable { return callable.call(); }
    133       @Override
    134       public Class<?> getReturnType() { return null; }
    135     });
    136   }
    137 
    138   /** Returns a {@link Behaviour} that throws the given {@link Throwable}. */
    139   public static <T extends Throwable> Behaviour doThrow(final T exception) {
    140     return new BehaviourImpl(new Action() {
    141       @Override
    142       public Object doAction(Method method, Object[] args) throws Throwable { throw exception; }
    143       @Override
    144       public Class<?> getReturnType() { return null; }
    145     });
    146   }
    147 
    148   /** Begins a verification step on a mock: the next method invocation on that mock will verify. */
    149   public static <T> T verify(T mock, CallCount howManyTimes) {
    150     return verify(mock, howManyTimes, null);
    151   }
    152 
    153   private static final class OrderChecker {
    154     private MethodCall mLastCall;
    155 
    156     public void checkOrder(List<MethodCall> calls, String fieldName) {
    157       MethodCall lastTrial = null;
    158       for (MethodCall trial : calls) {
    159         if (mLastCall == null || mLastCall.mInvocationOrder < trial.mInvocationOrder) {
    160           mLastCall = trial;
    161           return;
    162         }
    163         lastTrial = trial;
    164       }
    165       fail(formatFailedVerifyOrderMessage(mLastCall, lastTrial, fieldName));
    166     }
    167 
    168     private String formatFailedVerifyOrderMessage(MethodCall lastCall, MethodCall thisCall,
    169         String fieldName) {
    170       StringBuffer sb = new StringBuffer();
    171       sb.append("\nCall to:");
    172       appendDebugStringForMethodCall(sb, thisCall.mMethod, thisCall.mElement, fieldName, false);
    173       sb.append("\nShould have happened after:");
    174       appendDebugStringForMethodCall(sb, lastCall.mMethod, lastCall.mElement, fieldName, false);
    175       sb.append("\nBut the calls happened in the wrong order");
    176       sb.append("\n");
    177       return sb.toString();
    178     }
    179   }
    180 
    181   private static <T> T verify(T mock, CallCount howManyTimes, OrderChecker orderCounter) {
    182     if (howManyTimes == null) {
    183       throw new IllegalArgumentException("Can't pass null for howManyTimes parameter");
    184     }
    185     DefaultInvocationHandler handler = getHandlerFrom(mock);
    186     checkState(handler.mHowManyTimes == null, "Unfinished verify() statements");
    187     checkState(handler.mOrderCounter == null, "Unfinished verify() statements");
    188     checkState(handler.mStubbingAction == null, "Unfinished stubbing statements");
    189     checkNoMatchers();
    190     handler.mHowManyTimes = howManyTimes;
    191     handler.mOrderCounter = orderCounter;
    192     sUnfinishedCallCounts.add(howManyTimes);
    193     return handler.<T>getVerifyingMock();
    194   }
    195 
    196   /** The list of outstanding calls to verify() that haven't finished, used to check for errors. */
    197   private static List<CallCount> sUnfinishedCallCounts = new ArrayList<CallCount>();
    198 
    199   /** The list of outstanding calls to when() that haven't finished, used to check for errors. */
    200   private static List<Action> sUnfinishedStubbingActions = new ArrayList<Action>();
    201 
    202   /** Begins a verification step for exactly one method call. */
    203   public static <T> T verify(T mock) { return verify(mock, times(1)); }
    204 
    205   /** Assert that no method calls at all happened on these mocks. */
    206   public static void verifyZeroInteractions(Object... mocks) {
    207     checkNoMatchers();
    208     for (Object mock : mocks) {
    209       List<MethodCall> mMethodCalls = getHandlerFrom(mock).mRecordedCalls;
    210       expect(mMethodCalls.isEmpty(), "Mock expected zero interactions, had " + mMethodCalls);
    211     }
    212   }
    213 
    214   /** Assert that there are no unverified method calls on these mocks. */
    215   public static void verifyNoMoreInteractions(Object... mocks) {
    216     StackTraceElement callSite = new Exception().getStackTrace()[1];
    217     for (Object mock : mocks) {
    218       verifyNoMoreInteractions(mock, callSite);
    219     }
    220   }
    221 
    222   /** Check that there are no unverified actions on the given mock. */
    223   private static void verifyNoMoreInteractions(Object mock, StackTraceElement callSite) {
    224     checkNoMatchers();
    225     DefaultInvocationHandler handlerFrom = getHandlerFrom(mock);
    226     List<MethodCall> unverifiedCalls = new ArrayList<MethodCall>();
    227     for (MethodCall method : handlerFrom.mRecordedCalls) {
    228       if (!method.mWasVerified) {
    229         unverifiedCalls.add(method);
    230       }
    231     }
    232     if (unverifiedCalls.size() > 0) {
    233       StringBuffer sb = new StringBuffer();
    234       sb.append("\nWe found these unverified calls:");
    235       for (MethodCall method : unverifiedCalls) {
    236         appendDebugStringForMethodCall(sb, method.mMethod,
    237             method.mElement, handlerFrom.mFieldName, false);
    238       }
    239       sb.append("\n\nAfter final interaction was verified:\n");
    240       sb.append("  at ").append(callSite).append("\n");
    241       throw new AssertionError(sb.toString());
    242     }
    243   }
    244 
    245   /** Creates a {@link CallCount} that matches exactly the given number of calls. */
    246   public static CallCount times(long n) { return new CallCount(n, n); }
    247 
    248   /** Claims that the verified call must happen before the given timeout. */
    249   public static Timeout timeout(long timeoutMillis) {
    250     return new Timeout(1, 1, timeoutMillis);
    251   }
    252 
    253 /** Creates a {@link CallCount} that only matches if the method was never called. */
    254   public static CallCount never() { return new CallCount(0, 0); }
    255 
    256   /** Creates a {@link CallCount} that matches at least one method call. */
    257   public static CallCount atLeastOnce() { return new CallCount(1, Long.MAX_VALUE); }
    258 
    259   /** Creates a {@link CallCount} that matches any number of method calls, including none at all. */
    260   public static CallCount anyTimes() { return new CallCount(0, Long.MAX_VALUE); }
    261 
    262   /** Creates a {@link CallCount} that matches at least the given number of calls. */
    263   public static CallCount atLeast(long n) { return new CallCount(n, Long.MAX_VALUE); }
    264 
    265   /** Creates a {@link CallCount} that matches up to the given number of calls but no more. */
    266   public static CallCount atMost(long n) { return new CallCount(0, n); }
    267 
    268   /** Creates a {@link CallCount} that matches any number of calls between the two given bounds. */
    269   public static CallCount between(long lower, long upper) { return new CallCount(lower, upper); }
    270 
    271   /**
    272    * Creates an argument matcher that matches any object, don't use for primitives.
    273    * <p>
    274    * <b>Note</b>: This does not enforce that the object is of type {@code T}; use
    275    * {@link #isA(Class)} to do that.
    276    */
    277   public static <T> T anyObject() { return LittleMock.<T>addMatcher(new MatchAnything(), null); }
    278 
    279   /** Generates an argument matcher that matches any string. */
    280   public static String anyString() { return isA(String.class); }
    281 
    282   /** Generates an argument matcher that matches any int. */
    283   public static int anyInt() { return addMatcher(new MatchAnything(), 0); }
    284 
    285   /** Generates an argument matcher that matches any float. */
    286   public static float anyFloat() { return addMatcher(new MatchAnything(), 0f); }
    287 
    288   /** Generates an argument matcher that matches any double. */
    289   public static double anyDouble() { return addMatcher(new MatchAnything(), 0.0); }
    290 
    291   /** Generates an argument matcher that matches any boolean. */
    292   public static boolean anyBoolean() { return addMatcher(new MatchAnything(), false); }
    293 
    294   /** Generates an argument matcher that matches any short. */
    295   public static short anyShort() { return addMatcher(new MatchAnything(), (short) 0); }
    296 
    297   /** Generates an argument matcher that matches any char. */
    298   public static char anyChar() { return addMatcher(new MatchAnything(), '\u0000'); }
    299 
    300   /** Generates an argument matcher that matches any long. */
    301   public static long anyLong() { return addMatcher(new MatchAnything(), 0L); }
    302 
    303   /** Generates an argument matcher that matches any byte. */
    304   public static byte anyByte() { return addMatcher(new MatchAnything(), (byte) 0); }
    305 
    306   /** Generates an argument matcher that matches exactly this value. */
    307   public static <T> T eq(final T expected) {
    308     return addMatcher(new ArgumentMatcher() {
    309       @Override
    310       public boolean matches(Object value) {
    311         return areEqual(expected, value);
    312       }
    313     }, expected);
    314   }
    315 
    316   /** An argument matcher that matches any value of the given type or a subtype thereof. */
    317   public static <T> T isA(final Class<T> clazz) {
    318     return LittleMock.<T>addMatcher(new ArgumentMatcher() {
    319       @Override
    320       public boolean matches(Object value) {
    321         return value == null || clazz.isAssignableFrom(value.getClass());
    322       }
    323     }, null);
    324   }
    325 
    326   /**
    327    * Injects fields annotated with {@link Mock} with a newly created mock, and those
    328    * annotated with {@link Captor} with a suitable capture object.
    329    *
    330    * <p>This operation is recursive, and travels up the class hierarchy, in order to set all
    331    * suitably annotated fields.
    332    */
    333   public static void initMocks(Object instance) throws Exception {
    334     injectMocksForClass(instance, instance.getClass());
    335   }
    336 
    337   /** Recurse up the class hierarchy injecting mocks as we go, stopping when we reach Object. */
    338   private static void injectMocksForClass(Object instance, Class<?> clazz)
    339       throws Exception {
    340     if (clazz.equals(Object.class)) {
    341       return;
    342     }
    343     for (Field field : clazz.getDeclaredFields()) {
    344       if (field.getAnnotation(Mock.class) != null) {
    345         setField(field, instance, mock(field.getType(), field.getName()));
    346       } else if (field.getAnnotation(Captor.class) != null) {
    347         setField(field, instance, createCaptor());
    348       }
    349     }
    350     injectMocksForClass(instance, clazz.getSuperclass());
    351   }
    352 
    353   /**
    354    * Creates a correctly typed {@link ArgumentCaptor} , it's easier to use
    355    * {@link #initMocks(Object)}.
    356    */
    357   public static <T> ArgumentCaptor<T> createCaptor() {
    358     return new ArgumentCaptorImpl<T>();
    359   }
    360 
    361   /**
    362    * Create a correctly typed ArgumentCaptor that also works for primitive types.
    363    * For example, to capture an int, use
    364    * <code>ArgumentCaptor<Integer> c = createCaptor(Integer.class);</code>
    365    */
    366   public static <T> ArgumentCaptor<T> createCaptor(Class<T> clazz) {
    367     return new ArgumentCaptorImpl<T>(clazz);
    368   }
    369 
    370   /** Implementation of the {@link ArgumentCaptor} interface. */
    371   private static class ArgumentCaptorImpl<T extends Object> implements ArgumentCaptor<T> {
    372     private final ArrayList<T> mAllValues = new ArrayList<T>();
    373     private T mValue;
    374     private Class<T> mClass;
    375 
    376     private ArgumentCaptorImpl() {
    377         mClass = null;
    378     }
    379 
    380     private ArgumentCaptorImpl(Class<T> clazz) {
    381         mClass = clazz;
    382     }
    383 
    384     public void setValue(T value) {
    385       mValue = value;
    386       mAllValues.add(mValue);
    387     }
    388 
    389     @Override
    390     public T getValue() {
    391       return mValue;
    392     }
    393 
    394     @Override
    395     public List<T> getAllValues() {
    396       return mAllValues;
    397     }
    398 
    399     @Override
    400     public T capture() {
    401       if (mClass != null) {
    402         if (Integer.class.isAssignableFrom(mClass)) {
    403           return (T) LittleMock.<Integer>addMatcher(this, 0);
    404         }
    405         if (Float.class.isAssignableFrom(mClass)) {
    406           return (T) LittleMock.<Float>addMatcher(this, 0f);
    407         }
    408         if (Double.class.isAssignableFrom(mClass)) {
    409           return (T) LittleMock.<Double>addMatcher(this, 0.0);
    410         }
    411         if (Boolean.class.isAssignableFrom(mClass)) {
    412           return (T) LittleMock.<Boolean>addMatcher(this, false);
    413         }
    414         if (Short.class.isAssignableFrom(mClass)) {
    415           return (T) LittleMock.<Short>addMatcher(this, (short) 0);
    416         }
    417         if (Character.class.isAssignableFrom(mClass)) {
    418           return (T) LittleMock.<Character>addMatcher(this, '\u0000');
    419         }
    420         if (Long.class.isAssignableFrom(mClass)) {
    421           return (T) LittleMock.<Long>addMatcher(this, 0L);
    422         }
    423         if (Byte.class.isAssignableFrom(mClass)) {
    424           return (T) LittleMock.<Byte>addMatcher(this, (byte) 0);
    425         }
    426       }
    427       return LittleMock.<T>addMatcher(this, null);
    428     }
    429 
    430 
    431     @Override
    432     public boolean matches(Object value) {
    433       // A capture always matches any argument.
    434       // This is so that verify(mMock).someMethod(capture(mCapture)) will match any and all calls
    435       // to someMethod() and we will capture the values into mCapture.
    436       return true;
    437     }
    438   }
    439 
    440   /**
    441    * Creates a mock, more easily done via the {@link #initMocks(Object)} method.
    442    *
    443    * <p>Also if you use this method to create your mock, the field in the error messages will
    444    * be named the same as your class passed in, you only get the actual field name if you
    445    * use the annotation.
    446    *
    447    * @throws IllegalArgumentException if the class you pass in is null
    448    */
    449   public static <T> T mock(Class<T> clazz) {
    450     if (clazz == null) {
    451       throw new IllegalArgumentException("Class to mock was null");
    452     }
    453     return mock(clazz, getDefaultFieldNameFor(clazz));
    454   }
    455 
    456   /** Creates a mock, more easily done via the {@link #initMocks(Object)} method. */
    457   @SuppressWarnings("unchecked")
    458   private static <T> T mock(Class<T> clazz, String fieldName) {
    459     return (T) createProxy(clazz, new DefaultInvocationHandler(clazz, fieldName));
    460   }
    461 
    462   /** Pick a suitable name for a field of the given clazz. */
    463   private static String getDefaultFieldNameFor(Class<?> clazz) {
    464     return clazz.getSimpleName().substring(0, 1).toLowerCase()
    465         + clazz.getSimpleName().substring(1);
    466   }
    467 
    468   /** Clears out the expectations on these mocks. */
    469   public static void reset(Object... mocks) {
    470     for (Object mock : mocks) {
    471       getHandlerFrom(mock).reset();
    472     }
    473   }
    474 
    475   /** Use this in tear down to check for programming errors. */
    476   public static void checkForProgrammingErrorsDuringTearDown() {
    477     checkNoMatchers();
    478     checkNoUnfinishedCalls(sUnfinishedCallCounts, "verify()");
    479     checkNoUnfinishedCalls(sUnfinishedStubbingActions, "stubbing");
    480   }
    481 
    482   /** Helper function to check that there are no verify or stubbing commands outstanding. */
    483   private static void checkNoUnfinishedCalls(List<?> list, String type) {
    484     if (!list.isEmpty()) {
    485       list.clear();
    486       throw new IllegalStateException("Unfinished " + type + " statements");
    487     }
    488   }
    489 
    490   /** Implementation of {@link Behaviour}. */
    491   private static class BehaviourImpl implements Behaviour {
    492     private final Action mAction;
    493 
    494     private BehaviourImpl(Action action) {
    495       mAction = action;
    496     }
    497 
    498     @Override
    499     public <T> T when(T mock) {
    500       DefaultInvocationHandler handler = getHandlerFrom(mock);
    501       checkState(handler.mHowManyTimes == null, "Unfinished verify() statements");
    502       checkState(handler.mOrderCounter == null, "Unfinished verify() statements");
    503       checkState(handler.mStubbingAction == null, "Unfinished stubbing statements");
    504       handler.mStubbingAction = mAction;
    505       sUnfinishedStubbingActions.add(mAction);
    506       return handler.<T>getStubbingMock();
    507     }
    508   }
    509 
    510   /**
    511    * The static list of argument matchers, used in the next method call to the mock.
    512    *
    513    * <p>In order to support the syntax like this: verify(mFoo).someMethod(anyInt()), it is
    514    * required that the anyInt() method store the value somewhere for use when the someMethod
    515    * is invoked.  That somewhere has to be static.  I don't like it any more than you do.
    516    *
    517    * <p>The same goes for anything that is passed into the someMethod as an argument - be it
    518    * a capture(mCaptureString) or eq(5) or whatever.
    519    *
    520    * <p>Avoiding the use of statics requires that we change the syntax of the verify statement,
    521    * and I can't think of an elegant way of doing it, and in any case I really like the current
    522    * syntax, so for now a static variable it is.
    523    *
    524    * <p>This match arguments list should contain either zero elements (the next method call will
    525    * not use any argument matchers) or it should contain exactly one argument matcher for
    526    * every argument being passed to the next method call.  You can't mix argument matchers and
    527    * raw values.
    528    */
    529   private static final List<ArgumentMatcher> sMatchArguments = new ArrayList<ArgumentMatcher>();
    530 
    531   /** Global invocation order of every mock method call. */
    532   private static final AtomicLong sGlobalInvocationOrder = new AtomicLong();
    533 
    534   /** Encapsulates a single call of a method with associated arguments. */
    535   private static class MethodCall {
    536     /** The method call. */
    537     private final Method mMethod;
    538     /** The arguments provided at the time the call happened. */
    539     private final Object[] mArgs;
    540     /** The order in which this method call was invoked. */
    541     private final long mInvocationOrder;
    542     /** The line from the test that invoked the handler to create this method call. */
    543     private final StackTraceElement mElement;
    544     /** Keeps track of method calls that have been verified, for verifyNoMoreInteractions(). */
    545     public boolean mWasVerified = false;
    546 
    547     public MethodCall(Method method, StackTraceElement element, Object[] args) {
    548       mMethod = method;
    549       mElement = element;
    550       mArgs = args;
    551       mInvocationOrder = sGlobalInvocationOrder.getAndIncrement();
    552     }
    553 
    554     public boolean argsMatch(Object[] args) {
    555       return Arrays.equals(mArgs, args);
    556     }
    557 
    558     @Override
    559     public String toString() {
    560       return "MethodCall [method=" + mMethod + ", args=" + Arrays.toString(mArgs) + "]";
    561     }
    562   }
    563 
    564   private static boolean areMethodsSame(Method first, Method second) {
    565     return areEqual(first.getDeclaringClass(), second.getDeclaringClass()) &&
    566         areEqual(first.getName(), second.getName()) &&
    567         areEqual(first.getReturnType(), second.getReturnType()) &&
    568         Arrays.equals(first.getParameterTypes(), second.getParameterTypes());
    569   }
    570 
    571   private static boolean areEqual(Object a, Object b) {
    572     if (a == null) {
    573       return b == null;
    574     }
    575     return a.equals(b);
    576   }
    577 
    578   /**
    579    * Magically handles the invoking of method calls.
    580    *
    581    * <p>This object is in one of three states, default (where invoking methods returns default
    582    * values and records the call), verifying (where invoking method calls makes sure that those
    583    * method calls happen with the supplied arguments or matchers) or stubbing (where the next method
    584    * call tells us which arguments to match in order to perform the desired behaviour).
    585    */
    586   private static class DefaultInvocationHandler implements InvocationHandler {
    587     private static Method sEqualsMethod;
    588     private static Method sHashCodeMethod;
    589     private static Method sToStringMethod;
    590 
    591     static {
    592       try {
    593         sEqualsMethod = Object.class.getMethod("equals", Object.class);
    594         sHashCodeMethod = Object.class.getMethod("hashCode");
    595         sToStringMethod = Object.class.getMethod("toString");
    596       } catch (SecurityException e) {
    597         // Should never happen.
    598         throw new RuntimeException("Your JVM/classloader is broken", e);
    599       } catch (NoSuchMethodException e) {
    600         // Should never happen.
    601         throw new RuntimeException("Your JVM/classloader is broken", e);
    602       }
    603     }
    604 
    605     /** The class of the mocked objects. */
    606     private final Class<?> mClazz;
    607     /** The field name in which the mock is assigned. */
    608     private final String mFieldName;
    609 
    610     /** The list of method calls executed on the mock. */
    611     private List<MethodCall> mRecordedCalls = new CopyOnWriteArrayList<MethodCall>();
    612     /** The list of method calls that were stubbed out and their corresponding actions. */
    613     private List<StubbedCall> mStubbedCalls = new CopyOnWriteArrayList<StubbedCall>();
    614 
    615     /**
    616      * The number of times a given call should be verified.
    617      *
    618      * <p>It is not null when in the verification state, and it is actually used to determine if we
    619      * are in the verification state.
    620      *
    621      * <p>It is reset to null once the verification has occurred.
    622      */
    623     private CallCount mHowManyTimes = null;
    624     private OrderChecker mOrderCounter = null;
    625 
    626     /**
    627      * The action to be associated with the stubbed method.
    628      *
    629      * <p>It is not null when in the stubbing state, and it is actually used to determine if we are
    630      * in the stubbing state.
    631      */
    632     private Action mStubbingAction = null;
    633 
    634     /** Dynamic proxy used to verify calls against this mock. */
    635     private final Object mVerifyingMock;
    636 
    637     /** Dynamic proxy used to stub calls against this mock. */
    638     private final Object mStubbingMock;
    639 
    640     /**
    641      * Creates a new invocation handler for an object.
    642      *
    643      * @param clazz the class the object belongs to
    644      * @param fieldName The name to be used to refer to the object. This may either be the name of
    645      *        the field this mock will be stored into (in case it uses @Mock) or a suitable name to
    646      *        use to refer to the object in error messages, based on the name of the class itself.
    647      */
    648     public DefaultInvocationHandler(Class<?> clazz, String fieldName) {
    649       mClazz = clazz;
    650       mFieldName = fieldName;
    651       mVerifyingMock = createVerifyingMock(clazz);
    652       mStubbingMock = createStubbingMock(clazz);
    653     }
    654 
    655     // Safe if you call getHandlerFrom(mock).getVerifyingMock(), since this is guaranteed to be
    656     // of the same type as mock itself.
    657     @SuppressWarnings("unchecked")
    658     public <T> T getVerifyingMock() {
    659       return (T) mVerifyingMock;
    660     }
    661 
    662     // Safe if you call getHandlerFrom(mock).getStubbingMock(), since this is guaranteed to be
    663     // of the same type as mock itself.
    664     @SuppressWarnings("unchecked")
    665     public <T> T getStubbingMock() {
    666       return (T) mStubbingMock;
    667     }
    668 
    669     /** Used to check that we always stub and verify from the same thread. */
    670     private AtomicReference<Thread> mCurrentThread = new AtomicReference<Thread>();
    671 
    672     /** Check that we are stubbing and verifying always from the same thread. */
    673     private void checkThread() {
    674       Thread currentThread = Thread.currentThread();
    675       mCurrentThread.compareAndSet(null, currentThread);
    676       if (mCurrentThread.get() != currentThread) {
    677         throw new IllegalStateException("Must always mock and stub from one thread only.  "
    678             + "This thread: " + currentThread + ", the other thread: " + mCurrentThread.get());
    679       }
    680     }
    681 
    682     /** Generate the dynamic proxy that will handle verify invocations. */
    683     private Object createVerifyingMock(Class<?> clazz) {
    684       return createProxy(clazz, new InvocationHandler() {
    685         @Override
    686         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    687           checkThread();
    688           expect(mHowManyTimes != null, "verifying mock doesn't know how many times");
    689           try {
    690             ArgumentMatcher[] matchers = checkClearAndGetMatchers(method);
    691             StackTraceElement callSite = new Exception().getStackTrace()[2];
    692             MethodCall methodCall = new MethodCall(method, callSite, args);
    693             innerVerify(method, matchers, methodCall, proxy, callSite, mHowManyTimes, mOrderCounter);
    694             return defaultReturnValue(method.getReturnType());
    695           } finally {
    696             sUnfinishedCallCounts.remove(mHowManyTimes);
    697             mHowManyTimes = null;
    698             mOrderCounter = null;
    699           }
    700         }
    701       });
    702     }
    703 
    704     /** Generate the dynamic proxy that will handle stubbing invocations. */
    705     private Object createStubbingMock(Class<?> clazz) {
    706       return createProxy(clazz, new InvocationHandler() {
    707         @Override
    708         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    709           checkThread();
    710           expect(mStubbingAction != null, "stubbing mock doesn't know what action to perform");
    711           try {
    712             ArgumentMatcher[] matchers = checkClearAndGetMatchers(method);
    713             StackTraceElement callSite = new Exception().getStackTrace()[2];
    714             MethodCall methodCall = new MethodCall(method, callSite, args);
    715             innerStub(method, matchers, methodCall, callSite, mStubbingAction);
    716             return defaultReturnValue(method.getReturnType());
    717           } finally {
    718             sUnfinishedStubbingActions.remove(mStubbingAction);
    719             mStubbingAction = null;
    720           }
    721         }
    722       });
    723     }
    724 
    725     @Override
    726     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    727       StackTraceElement callSite = new Exception().getStackTrace()[2];
    728       MethodCall methodCall = new MethodCall(method, callSite, args);
    729       return innerRecord(method, args, methodCall, proxy, callSite);
    730     }
    731 
    732     /**
    733      * Checks whether the given method is one of the special object methods that should not
    734      * verified or stubbed.
    735      * <p>
    736      * If this is one of such methods, it throws an AssertionException.
    737      *
    738      * @param method the method to be checked
    739      * @param operation the name of the operation, used for generating a helpful message
    740      */
    741     private void checkSpecialObjectMethods(Method method, String operation) {
    742       if (areMethodsSame(method, sEqualsMethod)
    743           || areMethodsSame(method, sHashCodeMethod)
    744           || areMethodsSame(method, sToStringMethod)) {
    745         fail("cannot " + operation + " call to " + method);
    746       }
    747     }
    748 
    749     private void reset() {
    750       mRecordedCalls.clear();
    751       mStubbedCalls.clear();
    752       mHowManyTimes = null;
    753       mOrderCounter = null;
    754       mStubbingAction = null;
    755     }
    756 
    757     private Object innerRecord(Method method, final Object[] args,
    758             MethodCall methodCall, Object proxy, StackTraceElement callSite) throws Throwable {
    759       if (areMethodsSame(method, sEqualsMethod)) {
    760         // Use identify for equality, the default behavior on object.
    761         return proxy == args[0];
    762       } else if (areMethodsSame(method, sHashCodeMethod)) {
    763         // This depends on the fact that each mock has its own DefaultInvocationHandler.
    764         return hashCode();
    765       } else if (areMethodsSame(method, sToStringMethod)) {
    766         // This is used to identify this is a mock, e.g., in error messages.
    767         return "Mock<" + mClazz.getName() + ">";
    768       }
    769       mRecordedCalls.add(methodCall);
    770       for (StubbedCall stubbedCall : mStubbedCalls) {
    771         if (areMethodsSame(stubbedCall.mMethodCall.mMethod, methodCall.mMethod)) {
    772           if (stubbedCall.mMethodCall.argsMatch(methodCall.mArgs)) {
    773             methodCall.mWasVerified = true;
    774             return stubbedCall.mAction.doAction(method, args);
    775           }
    776         }
    777       }
    778       // If no stub is defined, return the default value.
    779       return defaultReturnValue(method.getReturnType());
    780     }
    781 
    782     private void innerStub(Method method, final ArgumentMatcher[] matchers, MethodCall methodCall,
    783         StackTraceElement callSite, final Action stubbingAction) {
    784       checkSpecialObjectMethods(method, "stub");
    785       checkThisActionCanBeUsedForThisMethod(method, stubbingAction, callSite);
    786       if (matchers.length == 0) {
    787         // If there are no matchers, then this is a simple stubbed method call with an action.
    788         mStubbedCalls.add(0, new StubbedCall(methodCall, stubbingAction));
    789         return;
    790       }
    791       // If there are matchers, then we need to make a new method call which matches only
    792       // when all the matchers match.  Further, the action that method call needs to take
    793       // is to first record the values into any captures that may be present, and only then
    794       // proceed to execute the original action.
    795       MethodCall matchMatchersMethodCall = new MethodCall(method, callSite, matchers) {
    796         @Override
    797         public boolean argsMatch(Object[] args) { return doMatchersMatch(matchers, args); }
    798       };
    799       Action setCapturesThenAction = new Action() {
    800         @Override
    801         public Object doAction(Method innerMethod, Object[] innerArgs) throws Throwable {
    802           setCaptures(matchers, innerArgs);
    803           return stubbingAction.doAction(innerMethod, innerArgs);
    804         }
    805         @Override
    806         public Class<?> getReturnType() {
    807           return stubbingAction.getReturnType();
    808         }
    809       };
    810       mStubbedCalls.add(0, new StubbedCall(matchMatchersMethodCall, setCapturesThenAction));
    811     }
    812 
    813     private void checkThisActionCanBeUsedForThisMethod(Method method, final Action stubbingAction,
    814         StackTraceElement callSite) {
    815       Class<?> methodType = method.getReturnType();
    816       Class<?> actionType = stubbingAction.getReturnType();
    817       if (actionType == null) {
    818         // We could not determine the type returned by this action at the time we
    819         // created it. At this time we cannot check that the returned value is
    820         // appropriate to the return type of the method.
    821         // However, if the type is not correct, any actual invocation of the method
    822         // will fail later on.
    823         return;
    824       }
    825       if (!methodType.isAssignableFrom(actionType)) {
    826         if (methodType.isPrimitive() &&
    827             actionType.equals(PRIMITIVE_TO_BOXED_LOOKUP.get(methodType))) {
    828           return;
    829         }
    830         StringBuffer sb = new StringBuffer();
    831         sb.append("\nCan't return ").append(actionType.getSimpleName()).append(" from stub for:");
    832         appendDebugStringForMethodCall(sb, method, callSite, mFieldName, true);
    833         sb.append("\n");
    834         throw new IllegalArgumentException(sb.toString());
    835       }
    836     }
    837 
    838     private boolean doMatchersMatch(ArgumentMatcher[] matchers, Object[] args) {
    839       for (int i = 0; i < matchers.length; ++i) {
    840         if (!matchers[i].matches(args[i])) {
    841           return false;
    842         }
    843       }
    844       return true;
    845     }
    846 
    847     private void innerVerify(Method method, ArgumentMatcher[] matchers, MethodCall methodCall,
    848         Object proxy, StackTraceElement callSite, CallCount callCount, OrderChecker orderCounter) {
    849       checkSpecialObjectMethods(method, "verify");
    850       List<MethodCall> calls = countMatchingInvocations(method, matchers, methodCall);
    851       long callTimeout = callCount.getTimeout();
    852       checkState(orderCounter == null || callTimeout == 0, "can't inorder verify with a timeout");
    853       if (callTimeout > 0) {
    854         long endTime = System.currentTimeMillis() + callTimeout;
    855         while (!callCount.matches(calls.size())) {
    856           try {
    857             Thread.sleep(1);
    858           } catch (InterruptedException e) {
    859             fail("interrupted whilst waiting to verify");
    860           }
    861           if (System.currentTimeMillis() > endTime) {
    862             fail(formatFailedVerifyMessage(methodCall, calls.size(), callTimeout, callCount));
    863           }
    864           calls = countMatchingInvocations(method, matchers, methodCall);
    865         }
    866       } else {
    867         if (orderCounter != null) {
    868             orderCounter.checkOrder(calls, mFieldName);
    869         } else if (!callCount.matches(calls.size())) {
    870           fail(formatFailedVerifyMessage(methodCall, calls.size(), 0, callCount));
    871         }
    872       }
    873     }
    874 
    875     private List<MethodCall> countMatchingInvocations(Method method, ArgumentMatcher[] matchers,
    876         MethodCall methodCall) {
    877       List<MethodCall> methodCalls = new ArrayList<MethodCall>();
    878       for (MethodCall call : mRecordedCalls) {
    879         if (areMethodsSame(call.mMethod, method)) {
    880           if ((matchers.length > 0 && doMatchersMatch(matchers, call.mArgs)) ||
    881               call.argsMatch(methodCall.mArgs)) {
    882             setCaptures(matchers, call.mArgs);
    883             methodCalls.add(call);
    884             call.mWasVerified  = true;
    885           }
    886         }
    887       }
    888       return methodCalls;
    889     }
    890 
    891     private String formatFailedVerifyMessage(MethodCall methodCall, int total, long timeoutMillis,
    892         CallCount callCount) {
    893       StringBuffer sb = new StringBuffer();
    894       sb.append("\nExpected ").append(callCount);
    895       if (timeoutMillis > 0) {
    896         sb.append(" within " + timeoutMillis + "ms");
    897       }
    898       sb.append(" to:");
    899       appendDebugStringForMethodCall(sb, methodCall.mMethod,
    900           methodCall.mElement, mFieldName, false);
    901       sb.append("\n\n");
    902       if (mRecordedCalls.size() == 0) {
    903         sb.append("No method calls happened on this mock");
    904       } else {
    905         sb.append("Method calls that did happen:");
    906         for (MethodCall recordedCall : mRecordedCalls) {
    907           appendDebugStringForMethodCall(sb, recordedCall.mMethod,
    908               recordedCall.mElement, mFieldName, false);
    909         }
    910       }
    911       sb.append("\n");
    912       return sb.toString();
    913     }
    914 
    915     /** All matchers that are captures will store the corresponding arg value. */
    916     // This suppress warning means that I'm calling setValue with something that I can't promise
    917     // is of the right type.  But I think it is unavoidable.  Certainly I could give a better
    918     // error message than the class cast exception you'll get when you try to retrieve the value.
    919     @SuppressWarnings("unchecked")
    920     private void setCaptures(ArgumentMatcher[] matchers, Object[] args) {
    921       for (int i = 0; i < matchers.length; ++i) {
    922         if (matchers[i] instanceof ArgumentCaptorImpl) {
    923           ArgumentCaptorImpl.class.cast(matchers[i]).setValue(args[i]);
    924         }
    925       }
    926     }
    927 
    928     /** An empty array of matchers, to optimise the toArray() call below. */
    929     private static final ArgumentMatcher[] EMPTY_MATCHERS_ARRAY = new ArgumentMatcher[0];
    930 
    931     /** Makes sure that we have the right number of MATCH_ARGUMENTS for the given method. */
    932     private ArgumentMatcher[] checkClearAndGetMatchers(Method method) {
    933       ArgumentMatcher[] matchers = sMatchArguments.toArray(EMPTY_MATCHERS_ARRAY);
    934       sMatchArguments.clear();
    935       if (matchers.length > 0 && method.getParameterTypes().length != matchers.length) {
    936         throw new IllegalArgumentException("You can't mix matchers and regular objects.");
    937       }
    938       return matchers;
    939     }
    940   }
    941 
    942   private static void appendDebugStringForMethodCall(StringBuffer sb, Method method,
    943       StackTraceElement callSite, String fieldName, boolean showReturnType) {
    944     sb.append("\n  ");
    945     if (showReturnType) {
    946       sb.append("(").append(method.getReturnType().getSimpleName()).append(") ");
    947     }
    948     sb.append(fieldName).append(".").append(method.getName()).append("(");
    949     int i = 0;
    950     for (Class<?> type : method.getParameterTypes()) {
    951       if (++i > 1) {
    952         sb.append(", ");
    953       }
    954       sb.append(type.getSimpleName());
    955     }
    956     sb.append(")\n  at ").append(callSite);
    957   }
    958 
    959   /** Call this function when you don't expect there to be any outstanding matcher objects. */
    960   private static void checkNoMatchers() {
    961     if (sMatchArguments.size() > 0) {
    962       sMatchArguments.clear();
    963       throw new IllegalStateException("You have outstanding matchers, must be programming error");
    964     }
    965   }
    966 
    967   /** A pairing of a method call and an action to be performed when that call happens. */
    968   private static class StubbedCall {
    969     private final MethodCall mMethodCall;
    970     private final Action mAction;
    971 
    972     public StubbedCall(MethodCall methodCall, Action action) {
    973       mMethodCall = methodCall;
    974       mAction = action;
    975     }
    976 
    977     @Override
    978     public String toString() {
    979       return "StubbedCall [methodCall=" + mMethodCall + ", action=" + mAction + "]";
    980     }
    981   }
    982 
    983   /** Represents an action to be performed as a result of a method call. */
    984   private interface Action {
    985     public Object doAction(Method method, Object[] arguments) throws Throwable;
    986     /** The type of the action, or null if we can't determine the type at stub time. */
    987     public Class<?> getReturnType();
    988   }
    989 
    990   /** Represents something capable of testing if it matches an argument or not. */
    991   public interface ArgumentMatcher {
    992     public boolean matches(Object value);
    993   }
    994 
    995   /** A matcher that matches any argument. */
    996   private static class MatchAnything implements ArgumentMatcher {
    997     @Override
    998     public boolean matches(Object value) { return true; }
    999   }
   1000 
   1001   /** Encapsulates the number of times a method is called, between upper and lower bounds. */
   1002   private static class CallCount {
   1003     private long mLowerBound;
   1004     private long mUpperBound;
   1005 
   1006     public CallCount(long lowerBound, long upperBound) {
   1007       mLowerBound = lowerBound;
   1008       mUpperBound = upperBound;
   1009     }
   1010 
   1011     /** Tells us if this call count matches a desired count. */
   1012     public boolean matches(long total) {
   1013       return total >= mLowerBound && total <= mUpperBound;
   1014     }
   1015 
   1016     /** Tells us how long we should block waiting for the verify to happen. */
   1017     public long getTimeout() {
   1018       return 0;
   1019     }
   1020 
   1021     public CallCount setLowerBound(long lowerBound) {
   1022       mLowerBound = lowerBound;
   1023       return this;
   1024     }
   1025 
   1026     public CallCount setUpperBound(long upperBound) {
   1027       mUpperBound = upperBound;
   1028       return this;
   1029     }
   1030 
   1031     @Override
   1032     public String toString() {
   1033       if (mLowerBound == mUpperBound) {
   1034         return "exactly " + mLowerBound + plural(" call", mLowerBound);
   1035       } else {
   1036         return "between " + mLowerBound + plural(" call", mLowerBound) + " and " +
   1037             mUpperBound + plural(" call", mUpperBound);
   1038       }
   1039     }
   1040   }
   1041 
   1042   /** Encapsulates adding number of times behaviour to a call count with timeout. */
   1043   public static final class Timeout extends CallCount {
   1044     private long mTimeoutMillis;
   1045 
   1046     public Timeout(long lowerBound, long upperBound, long timeoutMillis) {
   1047       super(lowerBound, upperBound);
   1048       mTimeoutMillis = timeoutMillis;
   1049     }
   1050 
   1051     @Override
   1052     public long getTimeout() {
   1053       return mTimeoutMillis;
   1054     }
   1055 
   1056     public CallCount times(int times) { return setLowerBound(times).setUpperBound(times); }
   1057     public CallCount atLeast(long n) { return setLowerBound(n).setUpperBound(Long.MAX_VALUE); }
   1058     public CallCount atLeastOnce() { return setLowerBound(1).setUpperBound(Long.MAX_VALUE); }
   1059     public CallCount between(long n, long m) { return setLowerBound(n).setUpperBound(m); }
   1060   }
   1061 
   1062   /** Helper method to add an 's' to a string iff the count is not 1. */
   1063   private static String plural(String prefix, long count) {
   1064     return (count == 1) ? prefix : (prefix + "s");
   1065   }
   1066 
   1067   /** Helps us implement the eq(), any() and capture() and other methods on one line. */
   1068   private static <T> T addMatcher(ArgumentMatcher argument, T value) {
   1069     sMatchArguments.add(argument);
   1070     return value;
   1071   }
   1072 
   1073   /** A custom argument matcher, should be used only for object arguments not primitives. */
   1074   public static <T> T matches(ArgumentMatcher argument) {
   1075     sMatchArguments.add(argument);
   1076     return null;
   1077   }
   1078 
   1079   /** Utility method to throw an AssertionError if an assertion fails. */
   1080   private static void expect(boolean result, String message) {
   1081     if (!result) {
   1082       fail(message);
   1083     }
   1084   }
   1085 
   1086   /** Throws an AssertionError exception with a message. */
   1087   private static void fail(String message) {
   1088     throw new AssertionError(message);
   1089   }
   1090 
   1091   /** Static mapping from class type to default value for that type. */
   1092   private static final Map<Class<?>, Object> DEFAULT_RETURN_VALUE_LOOKUP;
   1093   static {
   1094     DEFAULT_RETURN_VALUE_LOOKUP = new HashMap<Class<?>, Object>();
   1095     DEFAULT_RETURN_VALUE_LOOKUP.put(int.class, 0);
   1096     DEFAULT_RETURN_VALUE_LOOKUP.put(boolean.class, false);
   1097     DEFAULT_RETURN_VALUE_LOOKUP.put(byte.class, (byte) 0);
   1098     DEFAULT_RETURN_VALUE_LOOKUP.put(long.class, (long) 0);
   1099     DEFAULT_RETURN_VALUE_LOOKUP.put(short.class, (short) 0);
   1100     DEFAULT_RETURN_VALUE_LOOKUP.put(float.class, (float) 0);
   1101     DEFAULT_RETURN_VALUE_LOOKUP.put(double.class, (double) 0);
   1102     DEFAULT_RETURN_VALUE_LOOKUP.put(char.class, '\u0000');
   1103     DEFAULT_RETURN_VALUE_LOOKUP.put(String.class, null);
   1104   }
   1105 
   1106   /** Static lookup from primitive types to their boxed versions. */
   1107   private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_BOXED_LOOKUP;
   1108   static {
   1109     PRIMITIVE_TO_BOXED_LOOKUP = new HashMap<Class<?>, Class<?>>();
   1110     PRIMITIVE_TO_BOXED_LOOKUP.put(int.class, Integer.class);
   1111     PRIMITIVE_TO_BOXED_LOOKUP.put(boolean.class, Boolean.class);
   1112     PRIMITIVE_TO_BOXED_LOOKUP.put(byte.class, Byte.class);
   1113     PRIMITIVE_TO_BOXED_LOOKUP.put(long.class, Long.class);
   1114     PRIMITIVE_TO_BOXED_LOOKUP.put(short.class, Short.class);
   1115     PRIMITIVE_TO_BOXED_LOOKUP.put(float.class, Float.class);
   1116     PRIMITIVE_TO_BOXED_LOOKUP.put(double.class, Double.class);
   1117     PRIMITIVE_TO_BOXED_LOOKUP.put(char.class, Character.class);
   1118   }
   1119 
   1120   /** For a given class type, returns the default value for that type. */
   1121   private static Object defaultReturnValue(Class<?> returnType) {
   1122     return DEFAULT_RETURN_VALUE_LOOKUP.get(returnType);
   1123   }
   1124 
   1125   /** Gets a suitable class loader for use with the proxy. */
   1126   private static ClassLoader getClassLoader() {
   1127     return LittleMock.class.getClassLoader();
   1128   }
   1129 
   1130   /** Sets a member field on an object via reflection (can set private members too). */
   1131   private static void setField(Field field, Object object, Object value) throws Exception {
   1132     field.setAccessible(true);
   1133     field.set(object, value);
   1134     field.setAccessible(false);
   1135   }
   1136 
   1137   /** Helper method to throw an IllegalStateException if given condition is not met. */
   1138   private static void checkState(boolean condition, String message) {
   1139     if (!condition) {
   1140       throw new IllegalStateException(message);
   1141     }
   1142   }
   1143 
   1144   /** Helper method to throw an IllegalStateException if given condition is not met. */
   1145   private static void checkState(boolean condition) {
   1146     if (!condition) {
   1147       throw new IllegalStateException();
   1148     }
   1149   }
   1150 
   1151   /**
   1152    * If the input object is one of our mocks, returns the {@link DefaultInvocationHandler}
   1153    * we constructed it with.  Otherwise fails with {@link IllegalArgumentException}.
   1154    */
   1155   private static DefaultInvocationHandler getHandlerFrom(Object mock) {
   1156     try {
   1157       InvocationHandler invocationHandler = Proxy.getInvocationHandler(mock);
   1158       if (invocationHandler instanceof DefaultInvocationHandler) {
   1159         return (DefaultInvocationHandler) invocationHandler;
   1160       }
   1161     } catch (IllegalArgumentException expectedIfNotAProxy) {}
   1162     try {
   1163       Class<?> proxyBuilder = Class.forName("com.google.dexmaker.stock.ProxyBuilder");
   1164       Method getHandlerMethod = proxyBuilder.getMethod("getInvocationHandler", Object.class);
   1165       Object invocationHandler = getHandlerMethod.invoke(proxyBuilder, mock);
   1166       if (invocationHandler instanceof DefaultInvocationHandler) {
   1167         return (DefaultInvocationHandler) invocationHandler;
   1168       }
   1169     } catch (Exception expectedIfNotAProxyBuilderMock) {}
   1170     try {
   1171       // Try with javassist.
   1172       Class<?> proxyObjectClass = Class.forName("javassist.util.proxy.ProxyObject");
   1173       Method getHandlerMethod = proxyObjectClass.getMethod("getHandler");
   1174       Object methodHandler = getHandlerMethod.invoke(mock);
   1175       InvocationHandler invocationHandler = Proxy.getInvocationHandler(methodHandler);
   1176       Method getOriginalMethod = invocationHandler.getClass().getMethod("$$getOriginal");
   1177       Object original = getOriginalMethod.invoke(invocationHandler);
   1178       if (original instanceof DefaultInvocationHandler) {
   1179         return (DefaultInvocationHandler) original;
   1180       }
   1181     } catch (Exception expectedIfNotJavassistProxy) {}
   1182     throw new IllegalArgumentException("not a valid mock: " + mock);
   1183   }
   1184 
   1185   private static boolean canUseJavassist() {
   1186       try {
   1187           Class.forName("javassist.util.proxy.ProxyFactory");
   1188           return true;
   1189       } catch (Exception expectedIfNotJavassistProxy) {
   1190           return false;
   1191       }
   1192   }
   1193 
   1194   /** Create a dynamic proxy for the given class, delegating to the given invocation handler. */
   1195   private static Object createProxy(Class<?> clazz, final InvocationHandler handler) {
   1196     // Interfaces are simple.  Just proxy them using java.lang.reflect.Proxy.
   1197     if (clazz.isInterface()) {
   1198       return Proxy.newProxyInstance(getClassLoader(), new Class<?>[] { clazz }, handler);
   1199     }
   1200     // Try with javassist.
   1201     if (canUseJavassist()) {
   1202         try {
   1203           Class<?> proxyFactoryClass = Class.forName("javassist.util.proxy.ProxyFactory");
   1204           Object proxyFactory = proxyFactoryClass.newInstance();
   1205           Method setSuperclassMethod = proxyFactoryClass.getMethod("setSuperclass", Class.class);
   1206           setSuperclassMethod.invoke(proxyFactory, clazz);
   1207           Class<?> methodFilterClass = Class.forName("javassist.util.proxy.MethodFilter");
   1208           InvocationHandler methodFilterHandler = new InvocationHandler() {
   1209             @Override
   1210             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   1211               checkState(method.getName().equals("isHandled"));
   1212               checkState(args.length == 1);
   1213               checkState(args[0] instanceof Method);
   1214               Method invokedMethod = (Method) args[0];
   1215               String methodName = invokedMethod.getName();
   1216               Class<?>[] params = invokedMethod.getParameterTypes();
   1217               if ("equals".equals(methodName) && params.length == 1
   1218                   && Object.class.equals(params[0])) {
   1219                 return false;
   1220               }
   1221               if ("hashCode".equals(methodName) && params.length == 0) {
   1222                   return false;
   1223               }
   1224               if ("toString".equals(methodName) && params.length == 0) {
   1225                   return false;
   1226               }
   1227               if ("finalize".equals(methodName) && params.length == 0) {
   1228                   return false;
   1229               }
   1230               return true;
   1231             }
   1232           };
   1233           Object methodFilter = Proxy.newProxyInstance(getClassLoader(),
   1234               new Class<?>[] { methodFilterClass }, methodFilterHandler);
   1235           Method setFilterMethod = proxyFactoryClass.getMethod("setFilter", methodFilterClass);
   1236           setFilterMethod.invoke(proxyFactory, methodFilter);
   1237           Method createClassMethod = proxyFactoryClass.getMethod("createClass");
   1238           Class<?> createdClass = (Class<?>) createClassMethod.invoke(proxyFactory);
   1239           InvocationHandler methodHandlerHandler = new InvocationHandler() {
   1240             @SuppressWarnings("unused")
   1241             public InvocationHandler $$getOriginal() {
   1242               return handler;
   1243             }
   1244             @Override
   1245             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   1246               checkState(method.getName().equals("invoke"));
   1247               checkState(args.length == 4);
   1248               checkState(args[1] instanceof Method);
   1249               Method invokedMethod = (Method) args[1];
   1250               checkState(args[3] instanceof Object[]);
   1251               return handler.invoke(args[0], invokedMethod, (Object[]) args[3]);
   1252             }
   1253           };
   1254           Class<?> methodHandlerClass = Class.forName("javassist.util.proxy.MethodHandler");
   1255           Object methodHandler = Proxy.newProxyInstance(getClassLoader(),
   1256               new Class<?>[] { methodHandlerClass }, methodHandlerHandler);
   1257           Object proxy = unsafeCreateInstance(createdClass);
   1258           Class<?> proxyObjectClass = Class.forName("javassist.util.proxy.ProxyObject");
   1259           Method setHandlerMethod = proxyObjectClass.getMethod("setHandler", methodHandlerClass);
   1260           setHandlerMethod.invoke(proxy, methodHandler);
   1261           return proxy;
   1262         } catch (Exception e) {
   1263           // Not supported, something went wrong.  Fall through, try android dexmaker.
   1264           e.printStackTrace(System.err);
   1265         }
   1266     }
   1267     // So, this is a class.  First try using Android's ProxyBuilder from dexmaker.
   1268     try {
   1269       Class<?> proxyBuilder = Class.forName("com.google.dexmaker.stock.ProxyBuilder");
   1270       Method forClassMethod = proxyBuilder.getMethod("forClass", Class.class);
   1271       Object builder = forClassMethod.invoke(null, clazz);
   1272       Method dexCacheMethod = builder.getClass().getMethod("dexCache", File.class);
   1273       File directory = AppDataDirGuesser.getsInstance().guessSuitableDirectoryForGeneratedClasses();
   1274       builder = dexCacheMethod.invoke(builder, directory);
   1275       Method buildClassMethod = builder.getClass().getMethod("buildProxyClass");
   1276       Class<?> resultClass = (Class<?>) buildClassMethod.invoke(builder);
   1277       Object proxy = unsafeCreateInstance(resultClass);
   1278       Field handlerField = resultClass.getDeclaredField("$__handler");
   1279       handlerField.setAccessible(true);
   1280       handlerField.set(proxy, handler);
   1281       return proxy;
   1282     } catch (Exception e) {
   1283       throw new IllegalStateException("Could not mock this concrete class", e);
   1284     }
   1285   }
   1286 
   1287   /** Attempt to construct an instance of the class using hacky methods to avoid calling super. */
   1288   @SuppressWarnings("unchecked")
   1289   private static <T> T unsafeCreateInstance(Class<T> clazz) {
   1290     // try jvm
   1291     try {
   1292       Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
   1293       Field f = unsafeClass.getDeclaredField("theUnsafe");
   1294       f.setAccessible(true);
   1295       final Object unsafe = f.get(null);
   1296       final Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class);
   1297       return (T) allocateInstance.invoke(unsafe, clazz);
   1298     } catch (Exception ignored) {}
   1299     // try dalvikvm, pre-gingerbread
   1300     try {
   1301       final Method newInstance = ObjectInputStream.class.getDeclaredMethod(
   1302           "newInstance", Class.class, Class.class);
   1303       newInstance.setAccessible(true);
   1304       return (T) newInstance.invoke(null, clazz, Object.class);
   1305     } catch (Exception ignored) {}
   1306     // try dalvikvm, post-gingerbread
   1307     try {
   1308       Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod(
   1309           "getConstructorId", Class.class);
   1310       getConstructorId.setAccessible(true);
   1311       final int constructorId = (Integer) getConstructorId.invoke(null, Object.class);
   1312       final Method newInstance = ObjectStreamClass.class.getDeclaredMethod(
   1313           "newInstance", Class.class, int.class);
   1314       newInstance.setAccessible(true);
   1315       return (T) newInstance.invoke(null, clazz, constructorId);
   1316     } catch (Exception ignored) {}
   1317     // try dalvikvm, with change https://android-review.googlesource.com/#/c/52331/
   1318     try {
   1319       Method getConstructorId = ObjectStreamClass.class
   1320           .getDeclaredMethod("getConstructorId", Class.class);
   1321       getConstructorId.setAccessible(true);
   1322       final long constructorId = (Long) getConstructorId.invoke(null, Object.class);
   1323       final Method newInstance = ObjectStreamClass.class
   1324           .getDeclaredMethod("newInstance", Class.class, long.class);
   1325       newInstance.setAccessible(true);
   1326       return (T) newInstance.invoke(null, clazz, constructorId);
   1327     } catch (Exception ignored) {}
   1328     throw new IllegalStateException("unsafe create instance failed");
   1329   }
   1330 
   1331   /** See {@link LittleMock#inOrder(Object[])}. */
   1332   public interface InOrder {
   1333       <T> T verify(T mock);
   1334   }
   1335 
   1336   /**
   1337    * Used to verify that invocations happen in a given order.
   1338    * <p>
   1339    * Still slight experimental at the moment: you can only verify one method call at a time,
   1340    * and we ignore the mocks array you pass in as an argument, you may use the returned inorder
   1341    * to verify all mocks.
   1342    * <p>
   1343    * This implementation is simple: the InOrder you get from this call can be used to verify that
   1344    * a sequence of method calls happened in the order you specify.  Every verify you make with
   1345    * this InOrder will be compared with every other verify you made, to make sure that all the
   1346    * original invocations happened in exactly that same order.
   1347    */
   1348   public static InOrder inOrder(Object... mocks) {
   1349     return new InOrder() {
   1350       private final OrderChecker mChecker = new OrderChecker();
   1351       @Override
   1352       public <T> T verify(T mock) {
   1353         return LittleMock.verify(mock, times(1), mChecker);
   1354       }
   1355     };
   1356   }
   1357 }
   1358