LittleMock.java revision 00e20ef3c702f7388c98bdeee300d218c7871f4d
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 (expected == null) ? (value == null) : expected.equals(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  /**
327   * Create a correctly typed ArgumentCaptor that also works for primitive types.
328   * For example, to capture an int, use
329   * <code>ArgumentCaptor<Integer> c = createCaptor(Integer.class);</code>
330   */
331  public static <T> ArgumentCaptor<T> createCaptor(Class<T> clazz) {
332    return new ArgumentCaptorImpl<T>(clazz);
333  }
334
335  /** Implementation of the {@link ArgumentCaptor} interface. */
336  private static class ArgumentCaptorImpl<T extends Object> implements ArgumentCaptor<T> {
337    private final ArrayList<T> mAllValues = new ArrayList<T>();
338    private T mValue;
339    private Class<T> mClass;
340
341    private ArgumentCaptorImpl() {
342        mClass = null;
343    }
344
345    private ArgumentCaptorImpl(Class<T> clazz) {
346        mClass = clazz;
347    }
348
349    public void setValue(T value) {
350      mValue = value;
351      mAllValues.add(mValue);
352    }
353
354    @Override
355    public T getValue() {
356      return mValue;
357    }
358
359    @Override
360    public List<T> getAllValues() {
361      return mAllValues;
362    }
363
364    @Override
365    public T capture() {
366      if (mClass != null) {
367        if (Integer.class.isAssignableFrom(mClass)) {
368          return (T) LittleMock.<Integer>addMatcher(this, 0);
369        }
370        if (Float.class.isAssignableFrom(mClass)) {
371          return (T) LittleMock.<Float>addMatcher(this, 0f);
372        }
373        if (Double.class.isAssignableFrom(mClass)) {
374          return (T) LittleMock.<Double>addMatcher(this, 0.0);
375        }
376        if (Boolean.class.isAssignableFrom(mClass)) {
377          return (T) LittleMock.<Boolean>addMatcher(this, false);
378        }
379        if (Short.class.isAssignableFrom(mClass)) {
380          return (T) LittleMock.<Short>addMatcher(this, (short) 0);
381        }
382        if (Character.class.isAssignableFrom(mClass)) {
383          return (T) LittleMock.<Character>addMatcher(this, '\u0000');
384        }
385        if (Long.class.isAssignableFrom(mClass)) {
386          return (T) LittleMock.<Long>addMatcher(this, 0L);
387        }
388        if (Byte.class.isAssignableFrom(mClass)) {
389          return (T) LittleMock.<Byte>addMatcher(this, (byte) 0);
390        }
391      }
392      return LittleMock.<T>addMatcher(this, null);
393    }
394
395
396    @Override
397    public boolean matches(Object value) {
398      // A capture always matches any argument.
399      // This is so that verify(mMock).someMethod(capture(mCapture)) will match any and all calls
400      // to someMethod() and we will capture the values into mCapture.
401      return true;
402    }
403  }
404
405  /**
406   * Creates a mock, more easily done via the {@link #initMocks(Object)} method.
407   *
408   * <p>Also if you use this method to create your mock, the field in the error messages will
409   * be named the same as your class passed in, you only get the actual field name if you
410   * use the annotation.
411   *
412   * @throws IllegalArgumentException if the class you pass in is null
413   */
414  public static <T> T mock(Class<T> clazz) {
415    if (clazz == null) {
416      throw new IllegalArgumentException("Class to mock was null");
417    }
418    return mock(clazz, getDefaultFieldNameFor(clazz));
419  }
420
421  /** Creates a mock, more easily done via the {@link #initMocks(Object)} method. */
422  @SuppressWarnings("unchecked")
423  private static <T> T mock(Class<T> clazz, String fieldName) {
424    return (T) createProxy(clazz, new DefaultInvocationHandler(clazz, fieldName));
425  }
426
427  /** Pick a suitable name for a field of the given clazz. */
428  private static String getDefaultFieldNameFor(Class<?> clazz) {
429    return clazz.getSimpleName().substring(0, 1).toLowerCase()
430        + clazz.getSimpleName().substring(1);
431  }
432
433  /** Clears out the expectations on these mocks. */
434  public static void reset(Object... mocks) {
435    for (Object mock : mocks) {
436      getHandlerFrom(mock).reset();
437    }
438  }
439
440  /** Use this in tear down to check for programming errors. */
441  public static void checkForProgrammingErrorsDuringTearDown() {
442    checkNoMatchers();
443    checkNoUnfinishedCalls(sUnfinishedCallCounts, "verify()");
444    checkNoUnfinishedCalls(sUnfinishedStubbingActions, "stubbing");
445  }
446
447  /** Helper function to check that there are no verify or stubbing commands outstanding. */
448  private static void checkNoUnfinishedCalls(List<?> list, String type) {
449    if (!list.isEmpty()) {
450      list.clear();
451      throw new IllegalStateException("Unfinished " + type + " statements");
452    }
453  }
454
455  /** Implementation of {@link Behaviour}. */
456  private static class BehaviourImpl implements Behaviour {
457    private final Action mAction;
458
459    private BehaviourImpl(Action action) {
460      mAction = action;
461    }
462
463    @Override
464    public <T> T when(T mock) {
465      DefaultInvocationHandler handler = getHandlerFrom(mock);
466      checkState(handler.mHowManyTimes == null, "Unfinished verify() statements");
467      checkState(handler.mStubbingAction == null, "Unfinished stubbing statements");
468      handler.mStubbingAction = mAction;
469      sUnfinishedStubbingActions.add(mAction);
470      return handler.<T>getStubbingMock();
471    }
472  }
473
474  /**
475   * The static list of argument matchers, used in the next method call to the mock.
476   *
477   * <p>In order to support the syntax like this: verify(mFoo).someMethod(anyInt()), it is
478   * required that the anyInt() method store the value somewhere for use when the someMethod
479   * is invoked.  That somewhere has to be static.  I don't like it any more than you do.
480   *
481   * <p>The same goes for anything that is passed into the someMethod as an argument - be it
482   * a capture(mCaptureString) or eq(5) or whatever.
483   *
484   * <p>Avoiding the use of statics requires that we change the syntax of the verify statement,
485   * and I can't think of an elegant way of doing it, and in any case I really like the current
486   * syntax, so for now a static variable it is.
487   *
488   * <p>This match arguments list should contain either zero elements (the next method call will
489   * not use any argument matchers) or it should contain exactly one argument matcher for
490   * every argument being passed to the next method call.  You can't mix argument matchers and
491   * raw values.
492   */
493  private static final List<ArgumentMatcher> sMatchArguments = new ArrayList<ArgumentMatcher>();
494
495  /** Encapsulates a single call of a method with associated arguments. */
496  private static class MethodCall {
497    /** The method call. */
498    private final Method mMethod;
499    /** The arguments provided at the time the call happened. */
500    private final Object[] mArgs;
501    /** The line from the test that invoked the handler to create this method call. */
502    private final StackTraceElement mElement;
503    /** Keeps track of method calls that have been verified, for verifyNoMoreInteractions(). */
504    public boolean mWasVerified = false;
505
506    public MethodCall(Method method, StackTraceElement element, Object[] args) {
507      mMethod = method;
508      mElement = element;
509      mArgs = args;
510    }
511
512    public boolean argsMatch(Object[] args) {
513      return Arrays.equals(mArgs, args);
514    }
515
516    @Override
517    public String toString() {
518      return "MethodCall [method=" + mMethod + ", args=" + Arrays.toString(mArgs) + "]";
519    }
520  }
521
522  /**
523   * Magically handles the invoking of method calls.
524   *
525   * <p>This object is in one of three states, default (where invoking methods returns default
526   * values and records the call), verifying (where invoking method calls makes sure that those
527   * method calls happen with the supplied arguments or matchers) or stubbing (where the next method
528   * call tells us which arguments to match in order to perform the desired behaviour).
529   */
530  private static class DefaultInvocationHandler implements InvocationHandler {
531    private static Method sEqualsMethod;
532    private static Method sHashCodeMethod;
533    private static Method sToStringMethod;
534
535    static {
536      try {
537        sEqualsMethod = Object.class.getMethod("equals", Object.class);
538        sHashCodeMethod = Object.class.getMethod("hashCode");
539        sToStringMethod = Object.class.getMethod("toString");
540      } catch (SecurityException e) {
541        // Should never happen.
542        throw new RuntimeException("Your JVM/classloader is broken", e);
543      } catch (NoSuchMethodException e) {
544        // Should never happen.
545        throw new RuntimeException("Your JVM/classloader is broken", e);
546      }
547    }
548
549    /** The class of the mocked objects. */
550    private final Class<?> mClazz;
551    /** The field name in which the mock is assigned. */
552    private final String mFieldName;
553
554    /** The list of method calls executed on the mock. */
555    private List<MethodCall> mRecordedCalls = new CopyOnWriteArrayList<MethodCall>();
556    /** The list of method calls that were stubbed out and their corresponding actions. */
557    private List<StubbedCall> mStubbedCalls = new CopyOnWriteArrayList<StubbedCall>();
558
559    /**
560     * The number of times a given call should be verified.
561     *
562     * <p>It is not null when in the verification state, and it is actually used to determine if we
563     * are in the verification state.
564     *
565     * <p>It is reset to null once the verification has occurred.
566     */
567    private CallCount mHowManyTimes = null;
568
569    /**
570     * The action to be associated with the stubbed method.
571     *
572     * <p>It is not null when in the stubbing state, and it is actually used to determine if we are
573     * in the stubbing state.
574     */
575    private Action mStubbingAction = null;
576
577    /** Dynamic proxy used to verify calls against this mock. */
578    private final Object mVerifyingMock;
579
580    /** Dynamic proxy used to stub calls against this mock. */
581    private final Object mStubbingMock;
582
583    /**
584     * Creates a new invocation handler for an object.
585     *
586     * @param clazz the class the object belongs to
587     * @param fieldName The name to be used to refer to the object. This may either be the name of
588     *        the field this mock will be stored into (in case it uses @Mock) or a suitable name to
589     *        use to refer to the object in error messages, based on the name of the class itself.
590     */
591    public DefaultInvocationHandler(Class<?> clazz, String fieldName) {
592      mClazz = clazz;
593      mFieldName = fieldName;
594      mVerifyingMock = createVerifyingMock(clazz);
595      mStubbingMock = createStubbingMock(clazz);
596    }
597
598    // Safe if you call getHandlerFrom(mock).getVerifyingMock(), since this is guaranteed to be
599    // of the same type as mock itself.
600    @SuppressWarnings("unchecked")
601    public <T> T getVerifyingMock() {
602      return (T) mVerifyingMock;
603    }
604
605    // Safe if you call getHandlerFrom(mock).getStubbingMock(), since this is guaranteed to be
606    // of the same type as mock itself.
607    @SuppressWarnings("unchecked")
608    public <T> T getStubbingMock() {
609      return (T) mStubbingMock;
610    }
611
612    /** Used to check that we always stub and verify from the same thread. */
613    private AtomicReference<Thread> mCurrentThread = new AtomicReference<Thread>();
614
615    /** Check that we are stubbing and verifying always from the same thread. */
616    private void checkThread() {
617      Thread currentThread = Thread.currentThread();
618      mCurrentThread.compareAndSet(null, currentThread);
619      if (mCurrentThread.get() != currentThread) {
620        throw new IllegalStateException("Must always mock and stub from one thread only.  "
621            + "This thread: " + currentThread + ", the other thread: " + mCurrentThread.get());
622      }
623    }
624
625    /** Generate the dynamic proxy that will handle verify invocations. */
626    private Object createVerifyingMock(Class<?> clazz) {
627      return createProxy(clazz, new InvocationHandler() {
628        @Override
629        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
630          checkThread();
631          expect(mHowManyTimes != null, "verifying mock doesn't know how many times");
632          try {
633            ArgumentMatcher[] matchers = checkClearAndGetMatchers(method);
634            StackTraceElement callSite = new Exception().getStackTrace()[2];
635            MethodCall methodCall = new MethodCall(method, callSite, args);
636            innerVerify(method, matchers, methodCall, proxy, callSite, mHowManyTimes);
637            return defaultReturnValue(method.getReturnType());
638          } finally {
639            sUnfinishedCallCounts.remove(mHowManyTimes);
640            mHowManyTimes = null;
641          }
642        }
643      });
644    }
645
646    /** Generate the dynamic proxy that will handle stubbing invocations. */
647    private Object createStubbingMock(Class<?> clazz) {
648      return createProxy(clazz, new InvocationHandler() {
649        @Override
650        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
651          checkThread();
652          expect(mStubbingAction != null, "stubbing mock doesn't know what action to perform");
653          try {
654            ArgumentMatcher[] matchers = checkClearAndGetMatchers(method);
655            StackTraceElement callSite = new Exception().getStackTrace()[2];
656            MethodCall methodCall = new MethodCall(method, callSite, args);
657            innerStub(method, matchers, methodCall, callSite, mStubbingAction);
658            return defaultReturnValue(method.getReturnType());
659          } finally {
660            sUnfinishedStubbingActions.remove(mStubbingAction);
661            mStubbingAction = null;
662          }
663        }
664      });
665    }
666
667    @Override
668    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
669      StackTraceElement callSite = new Exception().getStackTrace()[2];
670      MethodCall methodCall = new MethodCall(method, callSite, args);
671      return innerRecord(method, args, methodCall, proxy, callSite);
672    }
673
674    /**
675     * Checks whether the given method is one of the special object methods that should not
676     * verified or stubbed.
677     * <p>
678     * If this is one of such methods, it throws an AssertionException.
679     *
680     * @param method the method to be checked
681     * @param operation the name of the operation, used for generating a helpful message
682     */
683    private void checkSpecialObjectMethods(Method method, String operation) {
684      if (method.equals(sEqualsMethod)
685          || method.equals(sHashCodeMethod)
686          || method.equals(sToStringMethod)) {
687        fail("cannot " + operation + " call to " + method);
688      }
689    }
690
691    private void reset() {
692      mRecordedCalls.clear();
693      mStubbedCalls.clear();
694      mHowManyTimes = null;
695      mStubbingAction = null;
696    }
697
698    private Object innerRecord(Method method, final Object[] args,
699            MethodCall methodCall, Object proxy, StackTraceElement callSite) throws Throwable {
700      if (method.equals(sEqualsMethod)) {
701        // Use identify for equality, the default behavior on object.
702        return proxy == args[0];
703      } else if (method.equals(sHashCodeMethod)) {
704        // This depends on the fact that each mock has its own DefaultInvocationHandler.
705        return hashCode();
706      } else if (method.equals(sToStringMethod)) {
707        // This is used to identify this is a mock, e.g., in error messages.
708        return "Mock<" + mClazz.getName() + ">";
709      }
710      mRecordedCalls.add(methodCall);
711      for (StubbedCall stubbedCall : mStubbedCalls) {
712        if (stubbedCall.mMethodCall.mMethod.equals(methodCall.mMethod)) {
713          if (stubbedCall.mMethodCall.argsMatch(methodCall.mArgs)) {
714            methodCall.mWasVerified = true;
715            return stubbedCall.mAction.doAction(method, args);
716          }
717        }
718      }
719      // If no stub is defined, return the default value.
720      return defaultReturnValue(method.getReturnType());
721    }
722
723    private void innerStub(Method method, final ArgumentMatcher[] matchers, MethodCall methodCall,
724        StackTraceElement callSite, final Action stubbingAction) {
725      checkSpecialObjectMethods(method, "stub");
726      checkThisActionCanBeUsedForThisMethod(method, stubbingAction, callSite);
727      if (matchers.length == 0) {
728        // If there are no matchers, then this is a simple stubbed method call with an action.
729        mStubbedCalls.add(0, new StubbedCall(methodCall, stubbingAction));
730        return;
731      }
732      // If there are matchers, then we need to make a new method call which matches only
733      // when all the matchers match.  Further, the action that method call needs to take
734      // is to first record the values into any captures that may be present, and only then
735      // proceed to execute the original action.
736      MethodCall matchMatchersMethodCall = new MethodCall(method, callSite, matchers) {
737        @Override
738        public boolean argsMatch(Object[] args) { return doMatchersMatch(matchers, args); }
739      };
740      Action setCapturesThenAction = new Action() {
741        @Override
742        public Object doAction(Method innerMethod, Object[] innerArgs) throws Throwable {
743          setCaptures(matchers, innerArgs);
744          return stubbingAction.doAction(innerMethod, innerArgs);
745        }
746        @Override
747        public Class<?> getReturnType() {
748          return stubbingAction.getReturnType();
749        }
750      };
751      mStubbedCalls.add(0, new StubbedCall(matchMatchersMethodCall, setCapturesThenAction));
752    }
753
754    private void checkThisActionCanBeUsedForThisMethod(Method method, final Action stubbingAction,
755        StackTraceElement callSite) {
756      Class<?> methodType = method.getReturnType();
757      Class<?> actionType = stubbingAction.getReturnType();
758      if (actionType == null) {
759        // We could not determine the type returned by this action at the time we
760        // created it. At this time we cannot check that the returned value is
761        // appropriate to the return type of the method.
762        // However, if the type is not correct, any actual invocation of the method
763        // will fail later on.
764        return;
765      }
766      if (!methodType.isAssignableFrom(actionType)) {
767        if (methodType.isPrimitive() &&
768            actionType.equals(PRIMITIVE_TO_BOXED_LOOKUP.get(methodType))) {
769          return;
770        }
771        StringBuffer sb = new StringBuffer();
772        sb.append("\nCan't return ").append(actionType.getSimpleName()).append(" from stub for:");
773        appendDebugStringForMethodCall(sb, method, callSite, mFieldName, true);
774        sb.append("\n");
775        throw new IllegalArgumentException(sb.toString());
776      }
777    }
778
779    private boolean doMatchersMatch(ArgumentMatcher[] matchers, Object[] args) {
780      for (int i = 0; i < matchers.length; ++i) {
781        if (!matchers[i].matches(args[i])) {
782          return false;
783        }
784      }
785      return true;
786    }
787
788    private void innerVerify(Method method, ArgumentMatcher[] matchers, MethodCall methodCall,
789        Object proxy, StackTraceElement callSite, CallCount callCount) {
790      checkSpecialObjectMethods(method, "verify");
791      int total = countMatchingInvocations(method, matchers, methodCall);
792      long callTimeout = callCount.getTimeout();
793      if (callTimeout > 0) {
794        long endTime = System.currentTimeMillis() + callTimeout;
795        while (!callCount.matches(total)) {
796          try {
797            Thread.sleep(1);
798          } catch (InterruptedException e) {
799            fail("interrupted whilst waiting to verify");
800          }
801          if (System.currentTimeMillis() > endTime) {
802            fail(formatFailedVerifyMessage(methodCall, total, callTimeout, callCount));
803          }
804          total = countMatchingInvocations(method, matchers, methodCall);
805        }
806      } else {
807        if (!callCount.matches(total)) {
808          fail(formatFailedVerifyMessage(methodCall, total, 0, callCount));
809        }
810      }
811    }
812
813    private int countMatchingInvocations(Method method, ArgumentMatcher[] matchers,
814        MethodCall methodCall) {
815      int total = 0;
816      for (MethodCall call : mRecordedCalls) {
817        if (call.mMethod.equals(method)) {
818          if ((matchers.length > 0 && doMatchersMatch(matchers, call.mArgs)) ||
819              call.argsMatch(methodCall.mArgs)) {
820            setCaptures(matchers, call.mArgs);
821            ++total;
822            call.mWasVerified  = true;
823          }
824        }
825      }
826      return total;
827    }
828
829    private String formatFailedVerifyMessage(MethodCall methodCall, int total, long timeoutMillis,
830        CallCount callCount) {
831      StringBuffer sb = new StringBuffer();
832      sb.append("\nExpected ").append(callCount);
833      if (timeoutMillis > 0) {
834        sb.append(" within " + timeoutMillis + "ms");
835      }
836      sb.append(" to:");
837      appendDebugStringForMethodCall(sb, methodCall.mMethod,
838          methodCall.mElement, mFieldName, false);
839      sb.append("\n\n");
840      if (mRecordedCalls.size() == 0) {
841        sb.append("No method calls happened on this mock");
842      } else {
843        sb.append("Method calls that did happen:");
844        for (MethodCall recordedCall : mRecordedCalls) {
845          appendDebugStringForMethodCall(sb, recordedCall.mMethod,
846              recordedCall.mElement, mFieldName, false);
847        }
848      }
849      sb.append("\n");
850      return sb.toString();
851    }
852
853    /** All matchers that are captures will store the corresponding arg value. */
854    // This suppress warning means that I'm calling setValue with something that I can't promise
855    // is of the right type.  But I think it is unavoidable.  Certainly I could give a better
856    // error message than the class cast exception you'll get when you try to retrieve the value.
857    @SuppressWarnings("unchecked")
858    private void setCaptures(ArgumentMatcher[] matchers, Object[] args) {
859      for (int i = 0; i < matchers.length; ++i) {
860        if (matchers[i] instanceof ArgumentCaptorImpl) {
861          ArgumentCaptorImpl.class.cast(matchers[i]).setValue(args[i]);
862        }
863      }
864    }
865
866    /** An empty array of matchers, to optimise the toArray() call below. */
867    private static final ArgumentMatcher[] EMPTY_MATCHERS_ARRAY = new ArgumentMatcher[0];
868
869    /** Makes sure that we have the right number of MATCH_ARGUMENTS for the given method. */
870    private ArgumentMatcher[] checkClearAndGetMatchers(Method method) {
871      ArgumentMatcher[] matchers = sMatchArguments.toArray(EMPTY_MATCHERS_ARRAY);
872      sMatchArguments.clear();
873      if (matchers.length > 0 && method.getParameterTypes().length != matchers.length) {
874        throw new IllegalArgumentException("You can't mix matchers and regular objects.");
875      }
876      return matchers;
877    }
878  }
879
880  private static void appendDebugStringForMethodCall(StringBuffer sb, Method method,
881      StackTraceElement callSite, String fieldName, boolean showReturnType) {
882    sb.append("\n  ");
883    if (showReturnType) {
884      sb.append("(").append(method.getReturnType().getSimpleName()).append(") ");
885    }
886    sb.append(fieldName).append(".").append(method.getName()).append("(");
887    int i = 0;
888    for (Class<?> type : method.getParameterTypes()) {
889      if (++i > 1) {
890        sb.append(", ");
891      }
892      sb.append(type.getSimpleName());
893    }
894    sb.append(")\n  at ").append(callSite);
895  }
896
897  /** Call this function when you don't expect there to be any outstanding matcher objects. */
898  private static void checkNoMatchers() {
899    if (sMatchArguments.size() > 0) {
900      sMatchArguments.clear();
901      throw new IllegalStateException("You have outstanding matchers, must be programming error");
902    }
903  }
904
905  /** A pairing of a method call and an action to be performed when that call happens. */
906  private static class StubbedCall {
907    private final MethodCall mMethodCall;
908    private final Action mAction;
909
910    public StubbedCall(MethodCall methodCall, Action action) {
911      mMethodCall = methodCall;
912      mAction = action;
913    }
914
915    @Override
916    public String toString() {
917      return "StubbedCall [methodCall=" + mMethodCall + ", action=" + mAction + "]";
918    }
919  }
920
921  /** Represents an action to be performed as a result of a method call. */
922  private interface Action {
923    public Object doAction(Method method, Object[] arguments) throws Throwable;
924    /** The type of the action, or null if we can't determine the type at stub time. */
925    public Class<?> getReturnType();
926  }
927
928  /** Represents something capable of testing if it matches an argument or not. */
929  /*package*/ interface ArgumentMatcher {
930    public boolean matches(Object value);
931  }
932
933  /** A matcher that matches any argument. */
934  private static class MatchAnything implements ArgumentMatcher {
935    @Override
936    public boolean matches(Object value) { return true; }
937  }
938
939  /** Encapsulates the number of times a method is called, between upper and lower bounds. */
940  private static class CallCount {
941    private long mLowerBound;
942    private long mUpperBound;
943
944    public CallCount(long lowerBound, long upperBound) {
945      mLowerBound = lowerBound;
946      mUpperBound = upperBound;
947    }
948
949    /** Tells us if this call count matches a desired count. */
950    public boolean matches(long total) {
951      return total >= mLowerBound && total <= mUpperBound;
952    }
953
954    /** Tells us how long we should block waiting for the verify to happen. */
955    public long getTimeout() {
956      return 0;
957    }
958
959    public CallCount setLowerBound(long lowerBound) {
960      mLowerBound = lowerBound;
961      return this;
962    }
963
964    public CallCount setUpperBound(long upperBound) {
965      mUpperBound = upperBound;
966      return this;
967    }
968
969    @Override
970    public String toString() {
971      if (mLowerBound == mUpperBound) {
972        return "exactly " + mLowerBound + plural(" call", mLowerBound);
973      } else {
974        return "between " + mLowerBound + plural(" call", mLowerBound) + " and " +
975            mUpperBound + plural(" call", mUpperBound);
976      }
977    }
978  }
979
980  /** Encapsulates adding number of times behaviour to a call count with timeout. */
981  public static final class Timeout extends CallCount {
982    private long mTimeoutMillis;
983
984    public Timeout(long lowerBound, long upperBound, long timeoutMillis) {
985      super(lowerBound, upperBound);
986      mTimeoutMillis = timeoutMillis;
987    }
988
989    @Override
990    public long getTimeout() {
991      return mTimeoutMillis;
992    }
993
994    public CallCount times(int times) { return setLowerBound(times).setUpperBound(times); }
995    public CallCount atLeast(long n) { return setLowerBound(n).setUpperBound(Long.MAX_VALUE); }
996    public CallCount atLeastOnce() { return setLowerBound(1).setUpperBound(Long.MAX_VALUE); }
997    public CallCount between(long n, long m) { return setLowerBound(n).setUpperBound(m); }
998  }
999
1000  /** Helper method to add an 's' to a string iff the count is not 1. */
1001  private static String plural(String prefix, long count) {
1002    return (count == 1) ? prefix : (prefix + "s");
1003  }
1004
1005  /** Helps us implement the eq(), any() and capture() and other methods on one line. */
1006  private static <T> T addMatcher(ArgumentMatcher argument, T value) {
1007    sMatchArguments.add(argument);
1008    return value;
1009  }
1010
1011  /** Utility method to throw an AssertionError if an assertion fails. */
1012  private static void expect(boolean result, String message) {
1013    if (!result) {
1014      fail(message);
1015    }
1016  }
1017
1018  /** Throws an AssertionError exception with a message. */
1019  private static void fail(String message) {
1020    throw new AssertionError(message);
1021  }
1022
1023  /** Static mapping from class type to default value for that type. */
1024  private static final Map<Class<?>, Object> DEFAULT_RETURN_VALUE_LOOKUP;
1025  static {
1026    DEFAULT_RETURN_VALUE_LOOKUP = new HashMap<Class<?>, Object>();
1027    DEFAULT_RETURN_VALUE_LOOKUP.put(int.class, 0);
1028    DEFAULT_RETURN_VALUE_LOOKUP.put(boolean.class, false);
1029    DEFAULT_RETURN_VALUE_LOOKUP.put(byte.class, (byte) 0);
1030    DEFAULT_RETURN_VALUE_LOOKUP.put(long.class, (long) 0);
1031    DEFAULT_RETURN_VALUE_LOOKUP.put(short.class, (short) 0);
1032    DEFAULT_RETURN_VALUE_LOOKUP.put(float.class, (float) 0);
1033    DEFAULT_RETURN_VALUE_LOOKUP.put(double.class, (double) 0);
1034    DEFAULT_RETURN_VALUE_LOOKUP.put(char.class, '\u0000');
1035    DEFAULT_RETURN_VALUE_LOOKUP.put(String.class, null);
1036  }
1037
1038  /** Static lookup from primitive types to their boxed versions. */
1039  private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_BOXED_LOOKUP;
1040  static {
1041    PRIMITIVE_TO_BOXED_LOOKUP = new HashMap<Class<?>, Class<?>>();
1042    PRIMITIVE_TO_BOXED_LOOKUP.put(int.class, Integer.class);
1043    PRIMITIVE_TO_BOXED_LOOKUP.put(boolean.class, Boolean.class);
1044    PRIMITIVE_TO_BOXED_LOOKUP.put(byte.class, Byte.class);
1045    PRIMITIVE_TO_BOXED_LOOKUP.put(long.class, Long.class);
1046    PRIMITIVE_TO_BOXED_LOOKUP.put(short.class, Short.class);
1047    PRIMITIVE_TO_BOXED_LOOKUP.put(float.class, Float.class);
1048    PRIMITIVE_TO_BOXED_LOOKUP.put(double.class, Double.class);
1049    PRIMITIVE_TO_BOXED_LOOKUP.put(char.class, Character.class);
1050  }
1051
1052  /** For a given class type, returns the default value for that type. */
1053  private static Object defaultReturnValue(Class<?> returnType) {
1054    return DEFAULT_RETURN_VALUE_LOOKUP.get(returnType);
1055  }
1056
1057  /** Gets a suitable class loader for use with the proxy. */
1058  private static ClassLoader getClassLoader() {
1059    return LittleMock.class.getClassLoader();
1060  }
1061
1062  /** Sets a member field on an object via reflection (can set private members too). */
1063  private static void setField(Field field, Object object, Object value) throws Exception {
1064    field.setAccessible(true);
1065    field.set(object, value);
1066    field.setAccessible(false);
1067  }
1068
1069  /** Helper method to throw an IllegalStateException if given condition is not met. */
1070  private static void checkState(boolean condition, String message) {
1071    if (!condition) {
1072      throw new IllegalStateException(message);
1073    }
1074  }
1075
1076  /**
1077   * If the input object is one of our mocks, returns the {@link DefaultInvocationHandler}
1078   * we constructed it with.  Otherwise fails with {@link IllegalArgumentException}.
1079   */
1080  private static DefaultInvocationHandler getHandlerFrom(Object mock) {
1081    try {
1082      InvocationHandler invocationHandler = Proxy.getInvocationHandler(mock);
1083      if (invocationHandler instanceof DefaultInvocationHandler) {
1084        return (DefaultInvocationHandler) invocationHandler;
1085      }
1086    } catch (IllegalArgumentException expectedIfNotAProxy) {}
1087    try {
1088      Class<?> proxyBuilder = Class.forName("com.google.dexmaker.stock.ProxyBuilder");
1089      Method getHandlerMethod = proxyBuilder.getMethod("getInvocationHandler", Object.class);
1090      Object invocationHandler = getHandlerMethod.invoke(proxyBuilder, mock);
1091      if (invocationHandler instanceof DefaultInvocationHandler) {
1092        return (DefaultInvocationHandler) invocationHandler;
1093      }
1094    } catch (Exception expectedIfNotAProxyBuilderMock) {}
1095    throw new IllegalArgumentException("not a valid mock: " + mock);
1096  }
1097
1098  /** Create a dynamic proxy for the given class, delegating to the given invocation handler. */
1099  private static Object createProxy(Class<?> clazz, InvocationHandler handler) {
1100    if (clazz.isInterface()) {
1101      return Proxy.newProxyInstance(getClassLoader(), new Class<?>[] { clazz }, handler);
1102    }
1103    try {
1104      Class<?> proxyBuilder = Class.forName("com.google.dexmaker.stock.ProxyBuilder");
1105      Method forClassMethod = proxyBuilder.getMethod("forClass", Class.class);
1106      Object builder = forClassMethod.invoke(null, clazz);
1107      Method dexCacheMethod = builder.getClass().getMethod("dexCache", File.class);
1108      File directory = AppDataDirGuesser.getsInstance().guessSuitableDirectoryForGeneratedClasses();
1109      builder = dexCacheMethod.invoke(builder, directory);
1110      Method buildClassMethod = builder.getClass().getMethod("buildProxyClass");
1111      Class<?> resultClass = (Class<?>) buildClassMethod.invoke(builder);
1112      Object proxy = unsafeCreateInstance(resultClass);
1113      Field handlerField = resultClass.getDeclaredField("$__handler");
1114      handlerField.setAccessible(true);
1115      handlerField.set(proxy, handler);
1116      return proxy;
1117    } catch (Exception e) {
1118      throw new IllegalStateException("Could not mock this concrete class", e);
1119    }
1120  }
1121
1122  /** Attempt to construct an instance of the class using hacky methods to avoid calling super. */
1123  @SuppressWarnings("unchecked")
1124  private static <T> T unsafeCreateInstance(Class<T> clazz) {
1125    // try dalvikvm, pre-gingerbread
1126    try {
1127      final Method newInstance = ObjectInputStream.class.getDeclaredMethod(
1128          "newInstance", Class.class, Class.class);
1129      newInstance.setAccessible(true);
1130      return (T) newInstance.invoke(null, clazz, Object.class);
1131    } catch (Exception ignored) {}
1132    // try dalvikvm, post-gingerbread
1133    try {
1134      Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod(
1135          "getConstructorId", Class.class);
1136      getConstructorId.setAccessible(true);
1137      final int constructorId = (Integer) getConstructorId.invoke(null, Object.class);
1138      final Method newInstance = ObjectStreamClass.class.getDeclaredMethod(
1139          "newInstance", Class.class, int.class);
1140      newInstance.setAccessible(true);
1141      return (T) newInstance.invoke(null, clazz, constructorId);
1142    } catch (Exception ignored) {}
1143    throw new IllegalStateException("unsafe create instance failed");
1144  }
1145}
1146