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