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