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