Home | History | Annotate | Download | only in littlemock
      1 /*
      2  * Copyright 2011 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *     http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.testing.littlemock;
     18 
     19 import static com.google.testing.littlemock.LittleMock.anyBoolean;
     20 import static com.google.testing.littlemock.LittleMock.anyByte;
     21 import static com.google.testing.littlemock.LittleMock.anyChar;
     22 import static com.google.testing.littlemock.LittleMock.anyDouble;
     23 import static com.google.testing.littlemock.LittleMock.anyFloat;
     24 import static com.google.testing.littlemock.LittleMock.anyInt;
     25 import static com.google.testing.littlemock.LittleMock.anyLong;
     26 import static com.google.testing.littlemock.LittleMock.anyObject;
     27 import static com.google.testing.littlemock.LittleMock.anyShort;
     28 import static com.google.testing.littlemock.LittleMock.anyString;
     29 import static com.google.testing.littlemock.LittleMock.anyTimes;
     30 import static com.google.testing.littlemock.LittleMock.atLeast;
     31 import static com.google.testing.littlemock.LittleMock.atLeastOnce;
     32 import static com.google.testing.littlemock.LittleMock.atMost;
     33 import static com.google.testing.littlemock.LittleMock.between;
     34 import static com.google.testing.littlemock.LittleMock.checkForProgrammingErrorsDuringTearDown;
     35 import static com.google.testing.littlemock.LittleMock.doAnswer;
     36 import static com.google.testing.littlemock.LittleMock.doNothing;
     37 import static com.google.testing.littlemock.LittleMock.doReturn;
     38 import static com.google.testing.littlemock.LittleMock.doThrow;
     39 import static com.google.testing.littlemock.LittleMock.eq;
     40 import static com.google.testing.littlemock.LittleMock.inOrder;
     41 import static com.google.testing.littlemock.LittleMock.initMocks;
     42 import static com.google.testing.littlemock.LittleMock.isA;
     43 import static com.google.testing.littlemock.LittleMock.matches;
     44 import static com.google.testing.littlemock.LittleMock.mock;
     45 import static com.google.testing.littlemock.LittleMock.never;
     46 import static com.google.testing.littlemock.LittleMock.reset;
     47 import static com.google.testing.littlemock.LittleMock.timeout;
     48 import static com.google.testing.littlemock.LittleMock.times;
     49 import static com.google.testing.littlemock.LittleMock.verify;
     50 import static com.google.testing.littlemock.LittleMock.verifyNoMoreInteractions;
     51 import static com.google.testing.littlemock.LittleMock.verifyZeroInteractions;
     52 
     53 import com.google.testing.littlemock.LittleMock.ArgumentMatcher;
     54 import com.google.testing.littlemock.LittleMock.InOrder;
     55 
     56 import junit.framework.TestCase;
     57 
     58 import java.io.IOException;
     59 import java.lang.reflect.InvocationHandler;
     60 import java.lang.reflect.Method;
     61 import java.lang.reflect.Proxy;
     62 import java.util.ArrayList;
     63 import java.util.List;
     64 import java.util.concurrent.Callable;
     65 import java.util.concurrent.CancellationException;
     66 import java.util.concurrent.CountDownLatch;
     67 import java.util.concurrent.ExecutionException;
     68 import java.util.concurrent.ExecutorService;
     69 import java.util.concurrent.Executors;
     70 import java.util.concurrent.Future;
     71 
     72 /**
     73  * Unit tests for the LittleMock class.
     74  *
     75  * @author hugohudson (at) gmail.com (Hugo Hudson)
     76  */
     77 public class LittleMockTest extends TestCase {
     78   @Mock private Foo mFoo;
     79   @Mock private Bar mBar;
     80   @Mock private BarSubtype mBarSubtype;
     81   @Captor private ArgumentCaptor<String> mCaptureString;
     82   @Captor private ArgumentCaptor<String> mCaptureAnotherString;
     83   @Captor private ArgumentCaptor<Integer> mCaptureInteger;
     84   @Captor private ArgumentCaptor<Callback> mCaptureCallback;
     85   private ExecutorService mExecutorService;
     86 
     87   @Override
     88   protected void setUp() throws Exception {
     89     super.setUp();
     90     LittleMock.initMocks(this);
     91     mExecutorService = Executors.newCachedThreadPool();
     92   }
     93 
     94   @Override
     95     protected void tearDown() throws Exception {
     96       mExecutorService.shutdown();
     97       super.tearDown();
     98     }
     99 
    100   /** Simple interface for testing against. */
    101   public interface Callback {
    102     public void callMeNow();
    103   }
    104 
    105   /** Simple interface for testing against. */
    106   public interface Foo {
    107     public int anInt();
    108     public boolean aBoolean();
    109     public byte aByte();
    110     public short aShort();
    111     public long aLong();
    112     public float aFloat();
    113     public double aDouble();
    114     public char aChar();
    115     public String aString();
    116     public Object anObject();
    117     public Foo anInterface();
    118     public void add(String input);
    119     public void clear();
    120     public String get(int index);
    121     public String lookup(String string);
    122     public void getResultLater(Callback callback);
    123     public String findByInt(int input);
    124     public String findByBoolean(boolean input);
    125     public String findByByte(byte input);
    126     public String findByShort(short input);
    127     public String findByLong(long input);
    128     public String findByFloat(float input);
    129     public String findByDouble(double input);
    130     public String findByChar(char input);
    131     public void takesObject(Object input);
    132     public void takesList(List<String> input);
    133     public void takesBar(Bar bar);
    134     public void exceptionThrower() throws Exception;
    135     public Bar aBar();
    136     public BarSubtype aBarSubtype();
    137   }
    138 
    139   /** Simple interface for testing against. */
    140   public interface Bar {
    141     public void doSomething();
    142     public String twoStrings(String first, String second);
    143     public void mixedArguments(int first, String second);
    144     public void getResultLater(Callback callback);
    145   }
    146 
    147   /** Subtype of Bar. */
    148   public interface BarSubtype extends Bar {
    149     public void doSomethingElse();
    150   }
    151 
    152   /** Another interface for testing with. */
    153   public interface OnClickListener {
    154     void onClick(Bar bar);
    155   }
    156 
    157   public void testDefaultReturnTypesForNewMocks() {
    158     assertEquals(0, mFoo.anInt());
    159     assertEquals(false, mFoo.aBoolean());
    160     assertEquals(0, mFoo.aByte());
    161     assertEquals(0, mFoo.aShort());
    162     assertEquals(0L, mFoo.aLong());
    163     assertEquals(0.0f, mFoo.aFloat());
    164     assertEquals(0.0d, mFoo.aDouble());
    165     assertEquals('\u0000', mFoo.aChar());
    166     assertEquals(null, mFoo.aString());
    167     assertEquals(null, mFoo.anObject());
    168     assertEquals(null, mFoo.anInterface());
    169   }
    170 
    171   public void testVerify_FailsIfNotDoneOnAProxy() {
    172     try {
    173       verify("hello").contains("something");
    174       fail();
    175     } catch (IllegalArgumentException expected) {}
    176   }
    177 
    178   public void testVerify_FailsIfNotCreatedByOurMockMethod() {
    179     try {
    180       verify(createNotARealMock()).add("something");
    181       fail();
    182     } catch (IllegalArgumentException expected) {}
    183   }
    184 
    185   public void testVerify_SuccessfulVerification() {
    186     mFoo.add("something");
    187     verify(mFoo).add("something");
    188   }
    189 
    190   public void testVerify_SuccessfulVerification_NormalOrder() {
    191     mFoo.add("something");
    192     mFoo.add("something else");
    193     verify(mFoo).add("something");
    194     verify(mFoo).add("something else");
    195   }
    196 
    197   public void testVerify_SuccessfulVerification_ReverseOrder() {
    198     mFoo.add("something");
    199     mFoo.add("something else");
    200     verify(mFoo).add("something else");
    201     verify(mFoo).add("something");
    202   }
    203 
    204   public void testVerify_MeansOnlyOnceSoShouldFailIfCalledTwice() {
    205     mFoo.add("something");
    206     mFoo.add("something");
    207     try {
    208       verify(mFoo).add("something");
    209       fail();
    210     } catch (AssertionError expected) {}
    211   }
    212 
    213   public void testVerify_FailedVerification_CalledWithWrongArgument() {
    214     mFoo.add("something else");
    215     try {
    216       verify(mFoo).add("something");
    217       fail();
    218     } catch (AssertionError expected) {}
    219   }
    220 
    221   public void testVerify_FailedVerification_WasNeverCalled() {
    222     try {
    223       verify(mFoo).add("something");
    224       fail();
    225     } catch (AssertionError expected) {}
    226   }
    227 
    228   public void testVerify_TimesTwice_Succeeds() {
    229     mFoo.add("jim");
    230     mFoo.add("jim");
    231     verify(mFoo, LittleMock.times(2)).add("jim");
    232   }
    233 
    234   public void testVerify_TimesTwice_ButThreeTimesFails() {
    235     mFoo.add("jim");
    236     mFoo.add("jim");
    237     mFoo.add("jim");
    238     try {
    239       verify(mFoo, LittleMock.times(2)).add("jim");
    240       fail();
    241     } catch (AssertionError expected) {}
    242   }
    243 
    244   public void testVerify_TimesTwice_ButOnceFails() {
    245     mFoo.add("jim");
    246     try {
    247       verify(mFoo, LittleMock.times(2)).add("jim");
    248       fail();
    249     } catch (AssertionError expected) {}
    250   }
    251 
    252   public void testVerify_TimesTwice_DifferentStringsFails() {
    253     mFoo.add("jim");
    254     mFoo.add("bob");
    255     try {
    256       verify(mFoo, LittleMock.times(2)).add("jim");
    257       fail();
    258     } catch (AssertionError expected) {}
    259   }
    260 
    261   public void testVerify_TimesTwice_WorksWithAnyString() {
    262     mFoo.add("jim");
    263     mFoo.add("bob");
    264     verify(mFoo, LittleMock.times(2)).add(anyString());
    265   }
    266 
    267   public void testVerify_TimesTwice_FailsIfJustOnceWithAnyString() {
    268     mFoo.add("bob");
    269     try {
    270       verify(mFoo, LittleMock.times(2)).add(anyString());
    271       fail();
    272     } catch (AssertionError expected) {}
    273   }
    274 
    275   public void testVerify_TimesTwice_FailsIfThreeTimesWithAnyString() {
    276     mFoo.add("bob");
    277     mFoo.add("jim");
    278     mFoo.add("james");
    279     try {
    280       verify(mFoo, LittleMock.times(2)).add(anyString());
    281       fail();
    282     } catch (AssertionError expected) {}
    283   }
    284 
    285   public void testVerify_Never_Succeeds() {
    286     verify(mFoo, never()).add("jim");
    287     verify(mFoo, never()).anInt();
    288   }
    289 
    290   public void testVerify_Never_FailsIfWasCalled() {
    291     mFoo.add("jim");
    292     try {
    293       verify(mFoo, never()).add("jim");
    294       fail();
    295     } catch (AssertionError expected) {}
    296   }
    297 
    298   public void testVerify_Never_PassesIfArgumentsDontMatch() {
    299     mFoo.add("bobby");
    300     verify(mFoo, never()).add("jim");
    301   }
    302 
    303   public void testVerify_AtLeastOnce_SuceedsForOneCall() {
    304     mFoo.add("jim");
    305     verify(mFoo, atLeastOnce()).add("jim");
    306   }
    307 
    308   public void testVerify_AtLeastOnce_SuceedsForThreeCalls() {
    309     mFoo.add("jim");
    310     mFoo.add("jim");
    311     mFoo.add("jim");
    312     verify(mFoo, atLeastOnce()).add("jim");
    313   }
    314 
    315   public void testVerify_AtLeastOnce_FailsForNoCalls() {
    316     try {
    317       verify(mFoo, atLeastOnce()).add("jim");
    318       fail();
    319     } catch (AssertionError expected) {}
    320   }
    321 
    322   public void testVerify_AtLeastThreeTimes_SuceedsForThreeCalls() {
    323     mFoo.add("jim");
    324     mFoo.add("jim");
    325     mFoo.add("jim");
    326     verify(mFoo, atLeast(3)).add("jim");
    327   }
    328 
    329   public void testVerify_AtLeastThreeTimes_SuceedsForFiveCalls() {
    330     mFoo.add("jim");
    331     mFoo.add("jim");
    332     mFoo.add("jim");
    333     mFoo.add("jim");
    334     mFoo.add("jim");
    335     verify(mFoo, atLeast(3)).add("jim");
    336   }
    337 
    338   public void testVerify_AtLeastThreeTimes_FailsForTwoCalls() {
    339     mFoo.add("jim");
    340     mFoo.add("jim");
    341     try {
    342       verify(mFoo, atLeast(3)).add("jim");
    343       fail();
    344     } catch (AssertionError expected) {}
    345   }
    346 
    347   public void testVerify_AtMostThreeTimes_SuceedsForThreeCalls() {
    348     mFoo.add("jim");
    349     mFoo.add("jim");
    350     mFoo.add("jim");
    351     verify(mFoo, atMost(3)).add("jim");
    352   }
    353 
    354   public void testVerify_AtMostThreeTimes_FailsForFiveCalls() {
    355     mFoo.add("jim");
    356     mFoo.add("jim");
    357     mFoo.add("jim");
    358     mFoo.add("jim");
    359     mFoo.add("jim");
    360     try {
    361       verify(mFoo, atMost(3)).add("jim");
    362       fail();
    363     } catch (AssertionError expected) {}
    364   }
    365 
    366   public void testVerify_AtMostThreeTimes_SucceedsForTwoCalls() {
    367     mFoo.add("jim");
    368     mFoo.add("jim");
    369     verify(mFoo, atMost(3)).add("jim");
    370   }
    371 
    372   public void testVerify_AtMostThreeTimes_SucceedsForNoCalls() {
    373     verify(mFoo, atMost(3)).add("jim");
    374   }
    375 
    376   public void testVerify_BetweenTwoAndFour_SucceedsForTwoCalls() {
    377     mFoo.add("jim");
    378     mFoo.add("jim");
    379     verify(mFoo, between(2, 4)).add("jim");
    380   }
    381 
    382   public void testVerify_BetweenTwoAndFour_SucceedsForFourCalls() {
    383     mFoo.add("jim");
    384     mFoo.add("jim");
    385     mFoo.add("jim");
    386     mFoo.add("jim");
    387     verify(mFoo, between(2, 4)).add("jim");
    388   }
    389 
    390   public void testVerify_BetweenTwoAndFour_FailsForOneCall() {
    391     mFoo.add("jim");
    392     try {
    393       verify(mFoo, between(2, 4)).add("jim");
    394       fail();
    395     } catch (AssertionError expected) {}
    396   }
    397 
    398   public void testVerify_BetweenTwoAndFour_FailsForFiveCalls() {
    399     mFoo.add("jim");
    400     mFoo.add("jim");
    401     mFoo.add("jim");
    402     mFoo.add("jim");
    403     mFoo.add("jim");
    404     try {
    405       verify(mFoo, LittleMock.between(2, 4)).add("jim");
    406       fail();
    407     } catch (AssertionError expected) {}
    408   }
    409 
    410   public void testDoReturnWhen_SimpleReturn() {
    411     doReturn("first").when(mFoo).get(0);
    412     assertEquals("first", mFoo.get(0));
    413   }
    414 
    415   public void testDoReturnWhen_LastStubCallWins() {
    416     doReturn("first").when(mFoo).get(0);
    417     doReturn("second").when(mFoo).get(0);
    418     assertEquals("second", mFoo.get(0));
    419   }
    420 
    421   public void testDoReturnWhen_CorrectStubMethodIsChosen() {
    422     doReturn("one").when(mFoo).get(1);
    423     doReturn("two").when(mFoo).get(2);
    424     assertEquals("one", mFoo.get(1));
    425     assertEquals("two", mFoo.get(2));
    426   }
    427 
    428   public void testDoReturnWhen_UnstubbedMethodStillReturnsDefault() {
    429     doReturn("one").when(mFoo).get(1);
    430     assertEquals(null, mFoo.get(2));
    431   }
    432 
    433   public void testDoReturnWhen_CalledOnString() {
    434     try {
    435       doReturn("first").when("hello").contains("something");
    436       fail();
    437     } catch (IllegalArgumentException expected) {}
    438   }
    439 
    440   public void testDoReturnWhen_CalledOnNonMock() {
    441     try {
    442       doReturn("first").when(createNotARealMock()).get(0);
    443       fail();
    444     } catch (IllegalArgumentException expected) {}
    445   }
    446 
    447   public void testDoReturnWhen_CanAlsoBeVerified() {
    448     // Mockito home page suggests that you don't verify stubbed calls.
    449     // I agree.  They support it anyway.  So will I.
    450     doReturn("one").when(mFoo).get(8);
    451     mFoo.get(8);
    452     verify(mFoo).get(8);
    453   }
    454 
    455   public void testDoReturn_CanPassIntForIntMethod() {
    456     doReturn(90).when(mFoo).anInt();
    457     assertEquals(90, mFoo.anInt());
    458   }
    459 
    460   // Interesting, you have to explicity convert the Integer class back into an int before it
    461   // is happy to accept this.
    462   public void testDoReturn_CanPassIntegerClassForIntMethod() {
    463     doReturn((int) Integer.valueOf(10)).when(mFoo).anInt();
    464     assertEquals(10, mFoo.anInt());
    465   }
    466 
    467   public void testDoReturn_PrimitiveLong() {
    468     doReturn((long) Long.valueOf(10L)).when(mFoo).aLong();
    469     assertEquals(10L, mFoo.aLong());
    470   }
    471 
    472   public void testDoReturn_PrimitiveTypes() {
    473     doReturn(5).when(mFoo).anInt();
    474     assertEquals(5, mFoo.anInt());
    475     doReturn((short) 5).when(mFoo).aShort();
    476     assertEquals(5, mFoo.aShort());
    477     doReturn(true).when(mFoo).aBoolean();
    478     assertEquals(true, mFoo.aBoolean());
    479     doReturn((byte) 3).when(mFoo).aByte();
    480     assertEquals(3, mFoo.aByte());
    481     doReturn(0.6f).when(mFoo).aFloat();
    482     assertEquals(0.6f, mFoo.aFloat());
    483     doReturn(0.7).when(mFoo).aDouble();
    484     assertEquals(0.7, mFoo.aDouble());
    485     doReturn('c').when(mFoo).aChar();
    486     assertEquals('c', mFoo.aChar());
    487     assertEquals(null, mFoo.anInterface());
    488   }
    489 
    490   public void testDoThrow_SimpleException() {
    491     doThrow(new RuntimeException()).when(mFoo).aDouble();
    492     try {
    493       mFoo.aDouble();
    494       fail();
    495     } catch (RuntimeException expected) {}
    496   }
    497 
    498   public void testDoThrow_IfItDoesntMatchItIsntThrown() {
    499     doThrow(new RuntimeException()).when(mFoo).aDouble();
    500     mFoo.aChar();
    501   }
    502 
    503   public void testDoThrow_KeepsThrowingForever() {
    504     doThrow(new RuntimeException()).when(mFoo).aDouble();
    505     try {
    506       mFoo.aDouble();
    507       fail();
    508     } catch (RuntimeException expected) {}
    509     // This second call should also throw a RuntimeException.
    510     try {
    511       mFoo.aDouble();
    512       fail();
    513     } catch (RuntimeException expected) {}
    514   }
    515 
    516   public void testDoNothing() {
    517     doNothing().when(mFoo).add("first");
    518     mFoo.add("first");
    519   }
    520 
    521   public void testVerifyZeroInteractions_PassesWhenNothingHasHappened() {
    522     verifyZeroInteractions(mFoo);
    523   }
    524 
    525   public void testVerifyZeroInteractions_FailsIfSomethingHasHappened() {
    526     mFoo.aBoolean();
    527     try {
    528       verifyZeroInteractions(mFoo);
    529       fail();
    530     } catch (AssertionError expected) {}
    531   }
    532 
    533   public void testVerifyZeroInteractions_HappyWithMultipleArguments() {
    534     verifyZeroInteractions(mFoo, mBar);
    535   }
    536 
    537   public void testVerifyZeroInteractions_ShouldFailEvenIfOtherInteractionsWereFirstVerified() {
    538     mFoo.add("test");
    539     verify(mFoo).add("test");
    540     try {
    541       verifyZeroInteractions(mFoo);
    542       fail();
    543     } catch (AssertionError expected) {}
    544   }
    545 
    546   public void testVerifyEq_Method() {
    547     mFoo.add("test");
    548     verify(mFoo).add(eq("test"));
    549   }
    550 
    551   public void testVerifyEq_MethodWithTwoSameTypeParameters() {
    552     mBar.twoStrings("first", "test");
    553     verify(mBar).twoStrings(eq("first"), eq("test"));
    554   }
    555 
    556   public void testVerifyEq_MethodWithTwoDifferentTypeParameters() {
    557     mBar.mixedArguments(8, "test");
    558     verify(mBar).mixedArguments(eq(8), eq("test"));
    559   }
    560 
    561   public void testVerifyEq_MethodFailsIfNotEqual() {
    562     mFoo.add("bob");
    563     try {
    564       verify(mFoo).add(eq("jim"));
    565       fail();
    566     } catch (AssertionError expected) {}
    567   }
    568 
    569   public void testVerifyEq_MethodFailsIfJustOneIsNotEqual() {
    570     mBar.twoStrings("first", "second");
    571     try {
    572       verify(mBar).twoStrings(eq("first"), eq("third"));
    573       fail();
    574     } catch (AssertionError expected) {}
    575   }
    576 
    577   public void testVerifyEq_MethodFailsIfSameParamsButInWrongOrder() {
    578     mBar.twoStrings("first", "second");
    579     try {
    580       verify(mBar).twoStrings(eq("second"), eq("first"));
    581       fail();
    582     } catch (AssertionError expected) {}
    583   }
    584 
    585   public void testCapture_SimpleCapture() {
    586     // We verify that there are zero matchers by using the check for programming errors method.
    587     checkForProgrammingErrorsDuringTearDown();
    588     mFoo.add("test");
    589     verify(mFoo).add(mCaptureString.capture());
    590     assertEquals("test", mCaptureString.getValue());
    591     checkForProgrammingErrorsDuringTearDown();
    592   }
    593 
    594   public void testCapture_DuringStubbing() {
    595     checkForProgrammingErrorsDuringTearDown();
    596     doReturn("hello").when(mFoo).lookup(mCaptureString.capture());
    597 
    598     assertEquals("hello", mFoo.lookup("what"));
    599     assertEquals("what", mCaptureString.getValue());
    600   }
    601 
    602   public void testCapture_TwoCallbacksDuringStubbing() {
    603     checkForProgrammingErrorsDuringTearDown();
    604     doNothing().when(mFoo).add(mCaptureString.capture());
    605     doNothing().when(mFoo).getResultLater(mCaptureCallback.capture());
    606 
    607     mFoo.add("hi");
    608     assertEquals("hi", mCaptureString.getValue());
    609 
    610     Callback callback = createNoOpCallback();
    611     mFoo.getResultLater(callback);
    612     assertEquals(callback, mCaptureCallback.getValue());
    613   }
    614 
    615   // TODO(hugohudson): 6. Is this impossible to fix?  You can't pass a
    616   // createCapture().capture() into a method expecting an int, because the capture
    617   // method returns null, and that gets auto-boxed to Integer on the way out of the
    618   // capture method, then auto-unboxed into an int when being passed to the underlying
    619   // method, which gives the NPE.  How best can we fix this?
    620   // It's not like you need to anyway - there's no point / need to capture a primitive,
    621   // just use eq(5) for example.
    622   public void testCapture_NPEWhenUnboxing() {
    623     try {
    624       mBar.mixedArguments(5, "ten");
    625       verify(mBar).mixedArguments(mCaptureInteger.capture(), mCaptureString.capture());
    626       // These lines are never reached, the previous line throws an NPE.
    627       fail("You shouldn't be able to reach here");
    628       assertEquals(Integer.valueOf(5), mCaptureInteger.getValue());
    629       assertEquals("ten", mCaptureString.getValue());
    630     } catch (NullPointerException e) {
    631       // Expected, unfortunately.
    632       // Now also we're in the situation where we have some captures hanging about in the static
    633       // variable, which will cause the tear down of this method to fail - we can clear them
    634       // as follows:
    635       try {
    636         checkForProgrammingErrorsDuringTearDown();
    637         fail("Expected an IllegalStateException");
    638       } catch (IllegalStateException e2) {
    639         // Expected.
    640       }
    641     }
    642   }
    643 
    644   public void testCapture_MultiCapture() {
    645     mFoo.lookup("james");
    646     mFoo.add("whinny");
    647     mFoo.add("jessica");
    648     verify(mFoo).lookup(mCaptureString.capture());
    649     verify(mFoo, atLeastOnce()).add(mCaptureAnotherString.capture());
    650     assertEquals("james", mCaptureString.getValue());
    651     assertEquals("jessica", mCaptureAnotherString.getValue());
    652     assertEquals(newList("whinny", "jessica"), mCaptureAnotherString.getAllValues());
    653   }
    654 
    655   public void testAnyString() {
    656     doReturn("jim").when(mFoo).lookup(anyString());
    657     assertEquals("jim", mFoo.lookup("barney"));
    658   }
    659 
    660   public void testAnyString_ObjectArgument() {
    661     // It can also be passed to a method that takes object.
    662     mFoo.takesObject("barney");
    663     verify(mFoo).takesObject(anyString());
    664   }
    665 
    666   public void testAnyString_ObjectValue() {
    667     mFoo.takesObject(new Object());
    668     try {
    669       verify(mFoo).takesObject(anyString());
    670       fail();
    671     } catch (AssertionError expected) {}
    672   }
    673 
    674   public void testAnyObject() {
    675     doReturn("jim").when(mFoo).lookup((String) anyObject());
    676     assertEquals("jim", mFoo.lookup("barney"));
    677   }
    678 
    679   public void testAnyPrimitives() {
    680     mFoo.findByBoolean(true);
    681     mFoo.findByInt(10000);
    682     mFoo.findByByte((byte) 250);
    683     mFoo.findByShort((short) 6666);
    684     mFoo.findByLong(13L);
    685     mFoo.findByFloat(8f);
    686     mFoo.findByDouble(1.1);
    687     mFoo.findByChar('h');
    688     verify(mFoo).findByBoolean(anyBoolean());
    689     verify(mFoo).findByInt(anyInt());
    690     verify(mFoo).findByByte(anyByte());
    691     verify(mFoo).findByShort(anyShort());
    692     verify(mFoo).findByLong(anyLong());
    693     verify(mFoo).findByFloat(anyFloat());
    694     verify(mFoo).findByDouble(anyDouble());
    695     verify(mFoo).findByChar(anyChar());
    696   }
    697 
    698   public void testAnyPrimitivesWhenMatching() {
    699     doReturn("a").when(mFoo).findByBoolean(anyBoolean());
    700     doReturn("b").when(mFoo).findByInt(anyInt());
    701     doReturn("c").when(mFoo).findByByte(anyByte());
    702     doReturn("d").when(mFoo).findByShort(anyShort());
    703     doReturn("e").when(mFoo).findByLong(anyLong());
    704     doReturn("f").when(mFoo).findByFloat(anyFloat());
    705     doReturn("g").when(mFoo).findByDouble(anyDouble());
    706     doReturn("h").when(mFoo).findByChar(anyChar());
    707     assertEquals("a", mFoo.findByBoolean(true));
    708     assertEquals("b", mFoo.findByInt(388));
    709     assertEquals("c", mFoo.findByByte((byte) 38));
    710     assertEquals("d", mFoo.findByShort((short) 16));
    711     assertEquals("e", mFoo.findByLong(1000000L));
    712     assertEquals("f", mFoo.findByFloat(15.3f));
    713     assertEquals("g", mFoo.findByDouble(13.3));
    714     assertEquals("h", mFoo.findByChar('i'));
    715   }
    716 
    717   public void testReset_NoInteractionsAfterReset() {
    718     mFoo.aByte();
    719     reset(mFoo);
    720     verifyZeroInteractions(mFoo);
    721   }
    722 
    723   public void testReset_VerifyFailsAfterReset() {
    724     mFoo.aByte();
    725     reset(mFoo);
    726     try {
    727       verify(mFoo).aByte();
    728       fail();
    729     } catch (AssertionError expected) {}
    730   }
    731 
    732   public void testCapture_BothBeforeAndAfter() {
    733     doNothing().when(mFoo).add(mCaptureString.capture());
    734     mFoo.add("first");
    735     verify(mFoo).add(mCaptureAnotherString.capture());
    736     assertEquals("first", mCaptureString.getValue());
    737     assertEquals("first", mCaptureAnotherString.getValue());
    738   }
    739 
    740   public void testDoAction_NormalOperation() {
    741     doAnswer(new Callable<Boolean>() {
    742       @Override
    743       public Boolean call() throws Exception {
    744         return Boolean.TRUE;
    745       }
    746     }).when(mFoo).aBoolean();
    747     assertEquals(true, mFoo.aBoolean());
    748   }
    749 
    750   public void testComplexSituationWithCallback() {
    751     // I want to specify that when hasCallback(Callback) method is called, the framework
    752     // should immediately call on the captured callback.
    753     doAnswer(new CallCapturedCallbackCallable())
    754         .when(mBar).getResultLater(mCaptureCallback.capture());
    755 
    756     // The test.
    757     mBar.getResultLater(new Callback() {
    758       @Override
    759       public void callMeNow() {
    760         mFoo.add("yes");
    761       }
    762     });
    763 
    764     verify(mFoo).add("yes");
    765   }
    766 
    767   public void testDoAction_CanThrowDeclaredException() throws Exception {
    768     doAnswer(new Callable<Void>() {
    769       @Override
    770       public Void call() throws Exception {
    771         throw new IOException("Problem");
    772       }
    773     }).when(mFoo).exceptionThrower();
    774     try {
    775       mFoo.exceptionThrower();
    776       fail();
    777     } catch (IOException expected) {}
    778   }
    779 
    780   public void testDoAction_CanThrowUndelcaredException() {
    781     doAnswer(new Callable<Void>() {
    782       @Override
    783       public Void call() throws Exception {
    784         throw new RuntimeException("Problem");
    785       }
    786     }).when(mFoo).aBoolean();
    787     try {
    788       mFoo.aBoolean();
    789       fail();
    790     } catch (RuntimeException expected) {}
    791   }
    792 
    793   public void testRunThisIsAnAliasForDoAction() {
    794     doAnswer(new Callable<Boolean>() {
    795       @Override
    796       public Boolean call() throws Exception {
    797         return Boolean.TRUE;
    798       }
    799     }).when(mFoo).aBoolean();
    800     assertEquals(true, mFoo.aBoolean());
    801   }
    802 
    803   public void testVerifyingTwice() {
    804     // Behaviour from Mockito docs online seems to be undefined for what should happen if you
    805     // try to verify the same behaviour twice.
    806     // I'm going to make a call on this one until I have more concrete information, and my
    807     // call is that it is okay to verify the same thing twice - a verify doesn't "consume"
    808     // the other verifications.
    809     // Thus this will pass:
    810     mFoo.aByte();
    811     verify(mFoo).aByte();
    812     verify(mFoo).aByte();
    813   }
    814 
    815   public void testVerifyNoMoreInteractions_SuccessWhenNoInteractions() {
    816     // Not absolutely certain how this is supposed to behave.
    817     // My guess is that every verify "tags" all the methods it verifies against.
    818     // Then verifyNoMoreInteractions() will pass only if there are no "untagged" method calls.
    819     // Thus, for a start, no interactions will pass.
    820     verifyNoMoreInteractions(mFoo, mBar);
    821   }
    822 
    823   public void testVerifyNoMoreInteractions_SuccessWhenOneActionWasVerified() {
    824     mFoo.aBoolean();
    825     verify(mFoo).aBoolean();
    826     verifyNoMoreInteractions(mFoo, mBar);
    827   }
    828 
    829   public void testVerifyNoMoreInteractions_FailsWhenOneActionWasNotVerified() {
    830     mFoo.aBoolean();
    831     try {
    832       verifyNoMoreInteractions(mFoo, mBar);
    833       fail();
    834     } catch (AssertionError expected) {}
    835   }
    836 
    837   public void testVerifyNoMoreInteractions_SucceedsWhenAllActionsWereVerified() {
    838     mFoo.get(3);
    839     mFoo.get(20);
    840     verify(mFoo, atLeastOnce()).get(anyInt());
    841     verifyNoMoreInteractions(mFoo);
    842   }
    843 
    844   public void testVerifyNoMoreInteractions_FailsWhenMostButNotAllActionsWereVerified() {
    845     mFoo.get(3);
    846     mFoo.get(20);
    847     mFoo.aByte();
    848     verify(mFoo, atLeastOnce()).get(anyInt());
    849     try {
    850       verifyNoMoreInteractions(mFoo);
    851       fail();
    852     } catch (AssertionError expected) {}
    853   }
    854 
    855   public void testVerifyNoMoreInteractions_ShouldIngoreStubbedCalls() {
    856     doReturn("hi").when(mFoo).get(8);
    857     mFoo.get(8);
    858     verifyNoMoreInteractions(mFoo);
    859   }
    860 
    861   public void testMatchers_WrongNumberOfMatchersOnStubbingCausesError() {
    862     try {
    863       doReturn("hi").when(mBar).twoStrings("jim", eq("bob"));
    864       fail();
    865     } catch (IllegalArgumentException expected) {}
    866   }
    867 
    868   public void testMatchers_WrongNumberOfMatchersOnVerifyCausesError() {
    869     try {
    870       verify(mBar).twoStrings("jim", eq("bob"));
    871       fail();
    872     } catch (IllegalArgumentException expected) {}
    873   }
    874 
    875   public void testCreateACaptureButDontUseItShouldFailAtNextVerify() {
    876     // If we create a capture illegally, outside of a method call, like so:
    877     mCaptureString.capture();
    878     // Then we will have illegally created an extra matcher object that we shouldn't have
    879     // created that is now sitting on the stack, and that will confuse the next true method
    880     // call on the mock object.
    881     // Thus we should check in the verify() method that there are *no matchers* on the static
    882     // list, as this would indicate a programming error such as the above.
    883     try {
    884       verify(mFoo, anyTimes()).aBoolean();
    885       fail();
    886     } catch (IllegalStateException expected) {}
    887   }
    888 
    889   public void testCreateACaptureButDontUseItShouldFailAtNextVerify_AlsoNoMoreInteractions() {
    890     // Same result desired as in previous test.
    891     mCaptureString.capture();
    892     try {
    893       verifyNoMoreInteractions(mFoo);
    894       fail();
    895     } catch (IllegalStateException expected) {}
    896   }
    897 
    898   public void testCreateACaptureButDontUseItShouldFailAtNextVerify_AlsoZeroInteraction() {
    899     mCaptureString.capture();
    900     try {
    901       verifyZeroInteractions(mFoo);
    902       fail();
    903     } catch (IllegalStateException expected) {}
    904   }
    905 
    906   public void testCheckStaticVariablesMethod() {
    907     // To help us avoid programming errors, I'm adding a method that you can call from tear down,
    908     // which will explode if there is anything still left in your static variables at the end
    909     // of the test (so that you know you did something wrong) and that also clears that static
    910     // variable (so that the next test won't fail).  It should fail if we create a matcher
    911     // be it a capture or anything else that is then not consumed.
    912     anyInt();
    913     try {
    914       checkForProgrammingErrorsDuringTearDown();
    915       fail();
    916     } catch (IllegalStateException expected) {}
    917   }
    918 
    919   public void testCantPassNullToVerifyCount() {
    920     try {
    921       verify(mFoo, null).aBoolean();
    922       fail();
    923     } catch (IllegalArgumentException expected) {}
    924   }
    925 
    926   public void testInjectionInNestedClasses() throws Exception {
    927     class Outer {
    928       @Mock protected Foo outerMock;
    929     }
    930     class Inner extends Outer {
    931       @Mock protected Foo innerMock;
    932     }
    933     Inner inner = new Inner();
    934     assertNull(inner.innerMock);
    935     assertNull(inner.outerMock);
    936     initMocks(inner);
    937     assertNotNull(inner.innerMock);
    938     assertNotNull(inner.outerMock);
    939   }
    940 
    941   public void testIsA_Succeeds() {
    942     mFoo.takesObject(new Object());
    943     verify(mFoo).takesObject(isA(Object.class));
    944   }
    945 
    946   public void testIsA_WithSubclass() {
    947     mFoo.takesObject("hello");
    948     verify(mFoo).takesObject(isA(Object.class));
    949     verify(mFoo).takesObject(isA(String.class));
    950   }
    951 
    952   public void testIsA_FailsWithSuperclass() {
    953     mFoo.takesObject(new Object());
    954     try {
    955       verify(mFoo).takesObject(isA(String.class));
    956       fail();
    957     } catch (AssertionError expected) {}
    958   }
    959 
    960   public void testIsA_WillAcceptNull() {
    961     mFoo.takesObject(null);
    962     verify(mFoo).takesObject(isA(Object.class));
    963     verify(mFoo).takesObject(isA(String.class));
    964   }
    965 
    966   public void testIsA_MatchSubtype() {
    967     mFoo.takesBar(mBarSubtype);
    968     verify(mFoo).takesBar(isA(BarSubtype.class));
    969   }
    970 
    971   public void testIsA_MatchSubtypeFailed() {
    972     mFoo.takesBar(mBar);
    973     try {
    974       verify(mFoo).takesBar(isA(BarSubtype.class));
    975       fail();
    976     } catch (AssertionError expected) {}
    977   }
    978 
    979   public void testVerifyEquals_ShouldFail() {
    980     mFoo.equals(null);
    981     try {
    982       verify(mFoo).equals(null);
    983       fail();
    984     } catch (AssertionError expected) {}
    985   }
    986 
    987   public void testVerifyHashCode_ShouldFail() {
    988     mFoo.hashCode();
    989     try {
    990       verify(mFoo).hashCode();
    991       fail();
    992     } catch (AssertionError expected) {}
    993   }
    994 
    995   public void testVerifyToString_ShouldFail() {
    996     mFoo.toString();
    997     try {
    998       verify(mFoo).toString();
    999       fail();
   1000     } catch (AssertionError expected) {}
   1001   }
   1002 
   1003   public void testStubEquals_ShouldFail() {
   1004     try {
   1005       doReturn(false).when(mFoo).equals(null);
   1006       fail();
   1007     } catch (AssertionError expected) {}
   1008   }
   1009 
   1010   public void testStubHashCode_ShouldFail() {
   1011     try {
   1012       doReturn(0).when(mFoo).hashCode();
   1013       fail();
   1014     } catch (AssertionError expected) {}
   1015   }
   1016 
   1017   public void testStubToString_ShouldFail() {
   1018     try {
   1019       doReturn("party").when(mFoo).toString();
   1020       fail();
   1021     } catch (AssertionError expected) {}
   1022   }
   1023 
   1024   public void testEqualsMethod_DoesntCountAsInteraction() {
   1025     mFoo.takesBar(mBar);
   1026     verify(mFoo).takesBar(mBar);
   1027     verifyNoMoreInteractions(mBar);
   1028   }
   1029 
   1030   public void testHashCodeMethod_DoesntCountAsInteraction() {
   1031     mFoo.hashCode();
   1032     verifyNoMoreInteractions(mFoo);
   1033   }
   1034 
   1035   public void testToStringMethod_DoesntCountAsInteraction() {
   1036     mFoo.toString();
   1037     verifyNoMoreInteractions(mFoo);
   1038   }
   1039 
   1040   public void testEquals_OnMock() {
   1041     assertTrue(mFoo.equals(mFoo));
   1042   }
   1043 
   1044   public void testHashCode_OnMock() {
   1045     // The hashCode() is checked against zero, the default int value, to make sure it is actually
   1046     // being treated differently.
   1047     // It is possible for a hashCode() to be zero, but very unlikely.
   1048     assertNotSame(0, mFoo.hashCode());
   1049   }
   1050 
   1051   public void testToString_OnMock() {
   1052     assertTrue(mFoo.toString().contains(Foo.class.getName()));
   1053   }
   1054 
   1055   public void testErrorMessages_NoArgMethodAndNoInteractions() {
   1056     /* I would like the error message to look like this:
   1057      * Expected exactly 2 calls to:
   1058      *   mFoo.aBoolean()
   1059      *   at the.line.where.the.verify.happened:xxx
   1060      *
   1061      * No method calls happened to this mock
   1062      */
   1063     int verifyLineNumber = 0;
   1064     try {
   1065       verifyLineNumber = getNextLineNumber();
   1066       verify(mFoo, times(2)).aBoolean();
   1067       fail("Should have thrown an assertion error");
   1068     } catch (AssertionError e) {
   1069       // Good, verify that the message is exactly as expected.
   1070       String expectedMessage =
   1071           "\nExpected exactly 2 calls to:\n"
   1072           + "  mFoo.aBoolean()\n"
   1073           + "  at " + singleLineStackTrace(verifyLineNumber) + "\n"
   1074           + "\n"
   1075           + "No method calls happened on this mock\n";
   1076       assertEquals(expectedMessage, e.getMessage());
   1077     }
   1078   }
   1079 
   1080   public void testErrorMessages_SomeArgsMethodAndSomeInteractions() {
   1081     /* I would like the error message to look like this:
   1082      * Expected exactly 1 call to:
   1083      *   mFoo.add(String)
   1084      *   at the.line.where.the.verify.happened:xxx
   1085      *
   1086      * Method calls that did happen:
   1087      *   mFoo.aByte()
   1088      *   at the.line.where.the.byte.happened:xxx
   1089      *   mFoo.findByBoolean(boolean)
   1090      *   at the line.where.the.boolean.happened:xxx
   1091      */
   1092     int aByteLineNumber = 0;
   1093     int findByBooleanLineNumber = 0;
   1094     int verifyLineNumber = 0;
   1095     try {
   1096       aByteLineNumber = getNextLineNumber();
   1097       mFoo.aByte();
   1098       findByBooleanLineNumber = getNextLineNumber();
   1099       mFoo.findByBoolean(true);
   1100       verifyLineNumber = getNextLineNumber();
   1101       verify(mFoo).add("jim");
   1102       fail("Should have thrown an assertion error");
   1103     } catch (AssertionError e) {
   1104       // Good, verify that the message is exactly as expected.
   1105       String expectedMessage =
   1106           "\nExpected exactly 1 call to:\n"
   1107           + "  mFoo.add(String)\n"
   1108           + "  at " + singleLineStackTrace(verifyLineNumber) + "\n"
   1109           + "\n"
   1110           + "Method calls that did happen:\n"
   1111           + "  mFoo.aByte()\n"
   1112           + "  at " + singleLineStackTrace(aByteLineNumber) + "\n"
   1113           + "  mFoo.findByBoolean(boolean)\n"
   1114           + "  at " + singleLineStackTrace(findByBooleanLineNumber) + "\n";
   1115       assertEquals(expectedMessage, e.getMessage());
   1116     }
   1117   }
   1118 
   1119   public void testErrorMessage_DoReturnExplainsWhatWentWrong() {
   1120     /* I would like the error message to look like this:
   1121      * Can't return Long from stub for:
   1122      *   (int) mFoo.anInt()
   1123      *   at the.line.where.the.assignment.happened:xxx
   1124      */
   1125     int lineNumber = 0;
   1126     try {
   1127       lineNumber = getNextLineNumber();
   1128       doReturn(10L).when(mFoo).anInt();
   1129       fail("Should have thrown an IllegalArgumentException");
   1130     } catch (IllegalArgumentException e) {
   1131       // Good, expected, verify the message.
   1132       String expectedMessage =
   1133           "\nCan't return Long from stub for:\n"
   1134           + "  (int) mFoo.anInt()\n"
   1135           + "  at " + singleLineStackTrace(lineNumber) + "\n";
   1136       assertEquals(expectedMessage, e.getMessage());
   1137     }
   1138   }
   1139 
   1140   public void testErrorMessage_DoReturnAlsoHasGoodErrorMessageForVoidMethods() {
   1141     /* I would like the error message to look like this:
   1142      * Can't return String from stub for:
   1143      *   (void) mFoo.add(String)
   1144      *   at the.line.where.the.assignment.happened:xxx
   1145      */
   1146     int lineNumber = 0;
   1147     try {
   1148       lineNumber = getNextLineNumber();
   1149       doReturn("hello").when(mFoo).add("jim");
   1150       fail("Should have thrown an IllegalArgumentException");
   1151     } catch (IllegalArgumentException e) {
   1152       // Good, expected, verify the message.
   1153       String expectedMessage =
   1154           "\nCan't return String from stub for:\n"
   1155           + "  (void) mFoo.add(String)\n"
   1156           + "  at " + singleLineStackTrace(lineNumber) + "\n";
   1157       assertEquals(expectedMessage, e.getMessage());
   1158     }
   1159   }
   1160 
   1161   public void testDoReturn_ThisShouldFailSinceDoubleIsNotAString() {
   1162     try {
   1163       doReturn("hello").when(mFoo).aDouble();
   1164       fail();
   1165     } catch (IllegalArgumentException expected) {}
   1166   }
   1167 
   1168   public void testDoReturn_ThisShouldPassSinceStringCanBeReturnedFromObjectMethod() {
   1169     doReturn("hello").when(mFoo).anObject();
   1170   }
   1171 
   1172   public void testDoReturn_ThisShouldFailSinceObjectCantBeReturnedFromString() {
   1173     try {
   1174       doReturn(new Object()).when(mFoo).aString();
   1175       fail();
   1176     } catch (IllegalArgumentException expected) {}
   1177   }
   1178 
   1179   public void testDoReturn_ThisShouldFailSinceBarIsNotSubtypeOfBarSubtype() {
   1180     try {
   1181       doReturn(mBar).when(mFoo).aBarSubtype();
   1182       fail();
   1183     } catch (IllegalArgumentException expected) {}
   1184   }
   1185 
   1186   public void testDoReturn_ThisShouldPassSinceBarSubTypeIsABar() {
   1187     doReturn(mBarSubtype).when(mFoo).aBar();
   1188   }
   1189 
   1190   // TODO(hugohudson): 7. Should fix this.
   1191 //  @ShouldThrow(IllegalArgumentException.class)
   1192   public void testDoReturn_ThisShouldFailBecauseNullIsNotAByte() {
   1193     doReturn(null).when(mFoo).aByte();
   1194   }
   1195 
   1196   // TODO(hugohudson): 7. Should fix this.
   1197   // Once we fix the previous test we won't need this one.
   1198   // I'm just demonstrating that currently this fails with NPE at use-time not at stub-time.
   1199   public void testDoReturn_ThisShouldFailBecauseNullIsNotAByte2() {
   1200     doReturn(null).when(mFoo).aByte();
   1201     try {
   1202       mFoo.aByte();
   1203       fail();
   1204     } catch (NullPointerException expected) {}
   1205   }
   1206 
   1207   public void testDoReturn_ThisShouldPassSinceNullIsAnObject() {
   1208     doReturn(null).when(mFoo).anObject();
   1209   }
   1210 
   1211   // TODO(hugohudson): 7. Should fix this.
   1212   // At present we aren't catching this, and would have difficulty doing so since we don't know
   1213   // the type of the callable.
   1214 //  @ShouldThrow(IllegalArgumentException.class)
   1215   public void testDoAnswer_ThisShouldFailSinceStringIsNotAByte() {
   1216     doAnswer(new Callable<String>() {
   1217       @Override public String call() throws Exception { return "hi"; }
   1218     }).when(mFoo).aByte();
   1219   }
   1220 
   1221   // TODO(hugohudson): 7. Should fix this to give proper message.
   1222   // We could at least give a good message saying why you get failure - saying that your string
   1223   // is not a byte, and pointing to where you stubbed it.
   1224   public void testDoAnswer_ThisShouldFailSinceStringIsNotAByte2() {
   1225     doAnswer(new Callable<String>() {
   1226       @Override public String call() throws Exception { return "hi"; }
   1227     }).when(mFoo).aByte();
   1228     try {
   1229       mFoo.aByte();
   1230       fail();
   1231     } catch (ClassCastException expected) {}
   1232   }
   1233 
   1234   public void testDoAnswer_ShouldHaveSimpleNameOnReturnValue() {
   1235     try {
   1236       doReturn("hi").when(mFoo).aBar();
   1237       fail();
   1238     } catch (IllegalArgumentException expected) {}
   1239   }
   1240 
   1241   public void testCantCreateMockOfNullType() {
   1242     try {
   1243       mock(null);
   1244       fail();
   1245     } catch (IllegalArgumentException expected) {}
   1246   }
   1247 
   1248   public void testCreateMockWithNullFieldName() {
   1249     OnClickListener mockClickListener = mock(OnClickListener.class);
   1250     try {
   1251       verify(mockClickListener).onClick(null);
   1252       fail();
   1253     } catch (AssertionError expected) {}
   1254   }
   1255 
   1256   public void testDoubleVerifyNoProblems() {
   1257     // Reusing a mock after a verify should be fine.
   1258     // There was a bug with this, let's check it doesn't regress.
   1259     mFoo.aBar();
   1260     verify(mFoo).aBar();
   1261 
   1262     mFoo.aByte();
   1263     verify(mFoo).aByte();
   1264   }
   1265 
   1266   public void testUnfinishedVerifyCaughtInTearDown_Issue5() {
   1267     verify(mFoo);
   1268     try {
   1269       checkForProgrammingErrorsDuringTearDown();
   1270       fail();
   1271     } catch (IllegalStateException expected) {}
   1272   }
   1273 
   1274   public void testUnfinishedWhenCaughtInTearDown_Issue5() {
   1275     doThrow(new RuntimeException()).when(mFoo);
   1276     try {
   1277       checkForProgrammingErrorsDuringTearDown();
   1278       fail();
   1279     } catch (IllegalStateException expected) {}
   1280   }
   1281 
   1282   public void testUnfinishedVerifyCaughtByStartingWhen_Issue5() {
   1283     verify(mFoo, never());
   1284     try {
   1285       doReturn(null).when(mFoo).clear();
   1286       fail();
   1287     } catch (IllegalStateException expected) {}
   1288   }
   1289 
   1290   public void testUnfinishedWhenCaughtByStartingVerify_Issue5() {
   1291     doThrow(new RuntimeException()).when(mFoo);
   1292     try {
   1293       verify(mFoo).clear();
   1294       fail();
   1295     } catch (IllegalStateException expected) {}
   1296   }
   1297 
   1298   public void testSecondUnfinishedVerifyShouldFailImmediately() throws Exception {
   1299     verify(mFoo);
   1300     try {
   1301       verify(mFoo);
   1302       fail();
   1303     } catch (IllegalStateException expected) {}
   1304   }
   1305 
   1306   public void testSecondUnfinishedWhenShouldFailImmediately() throws Exception {
   1307     doReturn(null).when(mFoo);
   1308     try {
   1309       doReturn(null).when(mFoo);
   1310       fail();
   1311     } catch (IllegalStateException expected) {}
   1312   }
   1313 
   1314   public void testVerifyWithTimeout_SuccessCase() throws Exception {
   1315     CountDownLatch countDownLatch = new CountDownLatch(1);
   1316     invokeBarMethodAfterLatchAwait(countDownLatch);
   1317     doReturn(null).when(mFoo).aBar();
   1318     verify(mFoo, never()).aBar();
   1319     countDownLatch.countDown();
   1320     verify(mFoo, timeout(100)).aBar();
   1321   }
   1322 
   1323   public void testVerifyWithTimeout_FailureCase() throws Exception {
   1324     long start = System.currentTimeMillis();
   1325     try {
   1326       verify(mFoo, timeout(10)).aBar();
   1327       fail();
   1328     } catch (AssertionError expected) {}
   1329     long duration = System.currentTimeMillis() - start;
   1330     assertTrue(duration > 5);
   1331   }
   1332 
   1333   public void testVerifyWithTimeoutMultipleInvocations_SuccessCase() throws Exception {
   1334     CountDownLatch countDownLatch = new CountDownLatch(1);
   1335     invokeBarMethodAfterLatchAwait(countDownLatch);
   1336     invokeBarMethodAfterLatchAwait(countDownLatch);
   1337     doReturn(null).when(mFoo).aBar();
   1338     verify(mFoo, never()).aBar();
   1339     countDownLatch.countDown();
   1340     verify(mFoo, timeout(100).times(2)).aBar();
   1341     verify(mFoo, timeout(100).atLeast(2)).aBar();
   1342     verify(mFoo, timeout(100).between(2, 4)).aBar();
   1343     verify(mFoo, timeout(100).atLeastOnce()).aBar();
   1344   }
   1345 
   1346   public void testVerifyWithTimeoutMultipleInvocations_FailureCase() throws Exception {
   1347     long start = System.currentTimeMillis();
   1348     mFoo.aBar();
   1349     try {
   1350       verify(mFoo, timeout(10).between(2, 3)).aBar();
   1351       fail();
   1352     } catch (AssertionError expected) {}
   1353     long duration = System.currentTimeMillis() - start;
   1354     assertTrue(duration > 5);
   1355 
   1356   }
   1357 
   1358   public void testConcurrentModificationExceptions() throws Exception {
   1359     // This test concurrently stubs, verifies, and uses a mock.
   1360     // It used to totally reproducibly throw a ConcurrentModificationException.
   1361     Future<?> task1 = mExecutorService.submit(new Runnable() {
   1362       @Override
   1363       public void run() {
   1364         while (!Thread.currentThread().isInterrupted()) {
   1365           mFoo.aBar();
   1366           Thread.yield();
   1367         }
   1368       }
   1369     });
   1370     Future<?> task2 = mExecutorService.submit(new Runnable() {
   1371         @Override
   1372         public void run() {
   1373           while (!Thread.currentThread().isInterrupted()) {
   1374             verify(mFoo, anyTimes()).aBar();
   1375             Thread.yield();
   1376           }
   1377         }
   1378       });
   1379     Thread.sleep(20);
   1380     task1.cancel(true);
   1381     task2.cancel(true);
   1382     try {
   1383       task1.get();
   1384       fail();
   1385     } catch (CancellationException expected) {}
   1386     try {
   1387       task2.get();
   1388       fail();
   1389     } catch (CancellationException expected) {}
   1390   }
   1391 
   1392   public void testCannotVerifyFromSecondThreadAfterStubbingInFirst() throws Exception {
   1393     doReturn(null).when(mFoo).aBar();
   1394     Future<?> submit = mExecutorService.submit(new Runnable() {
   1395       @Override
   1396       public void run() {
   1397         verify(mFoo, anyTimes()).aBar();
   1398       }
   1399     });
   1400     try {
   1401       submit.get();
   1402       fail();
   1403     } catch (ExecutionException expected) {
   1404       assertTrue(expected.getCause() instanceof IllegalStateException);
   1405     }
   1406   }
   1407 
   1408   public void testCannotStubFromSecondThreadAfterVerifyingInFirst() throws Exception {
   1409     mExecutorService.submit(new Runnable() {
   1410       @Override
   1411       public void run() {
   1412         verify(mFoo, anyTimes()).aBar();
   1413       }
   1414     }).get();
   1415     try {
   1416       doReturn(null).when(mFoo).aBar();
   1417       fail();
   1418     } catch (IllegalStateException expected) {}
   1419   }
   1420 
   1421   public void testCustomMatcher() {
   1422     ArgumentMatcher argumentMatcher = new ArgumentMatcher() {
   1423       @Override
   1424       public boolean matches(Object value) {
   1425         return ((String) value).contains("[]");
   1426       }
   1427     };
   1428     mFoo.add("as[]df");
   1429     mFoo.add("qwer[]asdf");
   1430     mFoo.add("1234");
   1431     verify(mFoo, times(3)).add(anyString());
   1432     verify(mFoo, times(2)).add((String) matches(argumentMatcher));
   1433   }
   1434 
   1435   public void testInorderExample_Success() {
   1436     @SuppressWarnings("unchecked")
   1437     List<String> firstMock = mock(List.class);
   1438     @SuppressWarnings("unchecked")
   1439     List<String> secondMock = mock(List.class);
   1440     firstMock.add("was called first");
   1441     secondMock.add("was called second");
   1442     InOrder inOrder = inOrder(firstMock, secondMock);
   1443     inOrder.verify(firstMock).add("was called first");
   1444     inOrder.verify(secondMock).add("was called second");
   1445   }
   1446 
   1447   public void testInorderExample_Failure() {
   1448     @SuppressWarnings("unchecked")
   1449     List<String> firstMock = mock(List.class);
   1450     @SuppressWarnings("unchecked")
   1451     List<String> secondMock = mock(List.class);
   1452     firstMock.add("was called first");
   1453     secondMock.add("was called second");
   1454     InOrder inOrder = inOrder(firstMock, secondMock);
   1455     inOrder.verify(secondMock).add("was called second");
   1456     try {
   1457       inOrder.verify(firstMock).add("was called first");
   1458       throw new IllegalStateException();
   1459     } catch (AssertionError expected) {}
   1460   }
   1461 
   1462   public void testInorderInterleave() {
   1463     @SuppressWarnings("unchecked")
   1464     List<String> firstMock = mock(List.class);
   1465     firstMock.add("a");
   1466     firstMock.add("b");
   1467     firstMock.add("a");
   1468 
   1469     // Should be fine to verify a then b, since they happened in that order.
   1470     InOrder inOrder = inOrder(firstMock);
   1471     inOrder.verify(firstMock).add("a");
   1472     inOrder.verify(firstMock).add("b");
   1473 
   1474     // Should also be fine to inorder verify the other way around, they happened in that order too.
   1475     inOrder = inOrder(firstMock);
   1476     inOrder.verify(firstMock).add("b");
   1477     inOrder.verify(firstMock).add("a");
   1478 
   1479     // Should be fine to verify "a, b, a" since that too happened.
   1480     inOrder = inOrder(firstMock);
   1481     inOrder.verify(firstMock).add("a");
   1482     inOrder.verify(firstMock).add("b");
   1483     inOrder.verify(firstMock).add("a");
   1484 
   1485     // "a, a, b" did not happen.
   1486     inOrder = inOrder(firstMock);
   1487     inOrder.verify(firstMock).add("a");
   1488     inOrder.verify(firstMock).add("a");
   1489     try {
   1490       inOrder.verify(firstMock).add("b");
   1491       throw new IllegalStateException();
   1492     } catch (AssertionError expected) {}
   1493 
   1494     // "b, a, b" did not happen.
   1495     inOrder = inOrder(firstMock);
   1496     inOrder.verify(firstMock).add("b");
   1497     inOrder.verify(firstMock).add("a");
   1498     try {
   1499       inOrder.verify(firstMock).add("b");
   1500       throw new IllegalStateException();
   1501     } catch (AssertionError expected) {}
   1502 
   1503     // "b" did not happen twice.
   1504     inOrder = inOrder(firstMock);
   1505     inOrder.verify(firstMock).add("b");
   1506     try {
   1507       inOrder.verify(firstMock).add("b");
   1508       throw new IllegalStateException();
   1509     } catch (AssertionError expected) {}
   1510   }
   1511 
   1512   public void testInorderComplicatedExample() {
   1513     // TODO: I'm currently totally ignoring the parameters passed to the inorder method.
   1514     // I don't understand what the point of them is, anyway.
   1515     @SuppressWarnings("unchecked")
   1516     List<String> firstMock = mock(List.class);
   1517     @SuppressWarnings("unchecked")
   1518     List<String> secondMock = mock(List.class);
   1519 
   1520     firstMock.add("1");
   1521     secondMock.add("2");
   1522     firstMock.add("3");
   1523     secondMock.add("4");
   1524 
   1525     InOrder allInOrder = inOrder(firstMock, secondMock);
   1526     allInOrder.verify(firstMock).add("1");
   1527     allInOrder.verify(secondMock).add("2");
   1528     allInOrder.verify(firstMock).add("3");
   1529     allInOrder.verify(secondMock).add("4");
   1530 
   1531     InOrder firstInOrder = inOrder(firstMock, secondMock);
   1532     firstInOrder.verify(firstMock).add("1");
   1533     firstInOrder.verify(firstMock).add("3");
   1534     try {
   1535       firstInOrder.verify(secondMock).add("2");
   1536       throw new IllegalStateException();
   1537     } catch (AssertionError expected) {}
   1538     firstInOrder.verify(secondMock).add("4");
   1539 
   1540     InOrder secondInOrder = inOrder(firstMock, secondMock);
   1541     secondInOrder.verify(secondMock).add("2");
   1542     secondInOrder.verify(secondMock).add("4");
   1543     try {
   1544       secondInOrder.verify(firstMock).add("1");
   1545       throw new IllegalStateException();
   1546     } catch (AssertionError expected) {}
   1547     try {
   1548       secondInOrder.verify(firstMock).add("3");
   1549       throw new IllegalStateException();
   1550     } catch (AssertionError expected) {}
   1551   }
   1552 
   1553   public static class Jim {
   1554     public int bob() {
   1555       fail();
   1556       return 3;
   1557     }
   1558   }
   1559 
   1560   // Does not work on JVM, android only.
   1561   public void testMockingConcreteClasses() throws Exception {
   1562     Jim mock = mock(Jim.class);
   1563     assertEquals(0, mock.bob());
   1564     doReturn(8).when(mock).bob();
   1565     assertEquals(8, mock.bob());
   1566   }
   1567 
   1568   private Future<Void> invokeBarMethodAfterLatchAwait(final CountDownLatch countDownLatch) {
   1569     return mExecutorService.submit(new Callable<Void>() {
   1570       @Override
   1571       public Void call() throws Exception {
   1572         countDownLatch.await();
   1573         mFoo.aBar();
   1574         return null;
   1575       }
   1576     });
   1577   }
   1578 
   1579   // TODO(hugohudson): 5. Every method that throws exceptions could be improved by adding
   1580   // test for the content of the error message.
   1581 
   1582   // TODO(hugohudson): 5. Make the doReturn() method take variable arguments.
   1583   // The syntax is:
   1584   // doReturn(1, 2, 3).when(mFoo).anInt();
   1585   // And of course means that the method returns 1 the first time, 2, the second and 3 the third.
   1586   // Note that this doesn't imply verification, and I presume that the 3 is always returned for
   1587   // the 4th and subsequent times.
   1588 
   1589   // TODO(hugohudson): 6. Could also offer a nicer syntax for multiple returns like this:
   1590   // How about doReturn().thenThrow().thenReturn().when(mFoo).aDouble();
   1591 
   1592   // TODO(hugohudson): 5. Get around to implementing Mockito's when() syntax.
   1593   // I don't really like it, because it means a lot more static nonsense, with yet more
   1594   // opportunities to shoot oneself in the foot.
   1595   // Plus, where's the upside in more than one way to do the same thing - it just gets confusing.
   1596   // But, I imagine that plenty of people who are familiar with Mockito will want this, so I
   1597   // probably should do it, plus there's a good argument that it allows typechecking of the
   1598   // method calls, so I guess we probably should.  Looks like this:
   1599   // when(mock.foo(0)).thenReturn(1);
   1600   // when(mock.foo(1)).thenThrow(new RuntimeException)
   1601   // when(mock.foo(anyInt())).thenReturn("bar")
   1602   // when(mock.foo(argThat(isValid()))).thenReturn("element")
   1603   // when(mock.someMethod("some arg")).thenThrow(new RuntimeException()).thenReturn("foo");
   1604   // when(mock.someMethod("some arg")).thenReturn("one", "two", "three");
   1605   // when(mock.someMethod(anyString())).thenAnswer(new Answer() {
   1606   //   @Override
   1607   //   Object answer(InvocationOnMock invocation) {
   1608   //     Object[] args = invocation.getArguments();
   1609   //     Object mock = invocation.getMock();
   1610   //     return "called with arguments: " + args;
   1611   //   }
   1612   // }
   1613 
   1614   // TODO(hugohudson): 6. Again we can chain things like doNothing() then doThrow() I suppose.
   1615   // doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod();
   1616 
   1617   // TODO(hugohudson): 6. I really like the idea of implementing the Spy, which is a wrapper on
   1618   // a real object and delegates all calls to that real object, but allows you to intercept
   1619   // the ones that you want to.
   1620   // Sounds like it will be particularly good for testing legacy code.
   1621   // But also wouldn't be so much use without us being able to mock concrete classes, which I
   1622   // imagine is not on the cards for a while yet.
   1623 
   1624   // TODO(hugohudson): 6. Could possibly look into more aliases for the common methods, so that
   1625   // you can do the 'given... when... assertThat...' pattern as follows:
   1626   //  //given
   1627   //  given(seller.askForBread()).willReturn(new Bread());
   1628   //  //when
   1629   //  Goods goods = shop.buyBread();
   1630   //  //then
   1631   //  assertThat(goods, containBread());
   1632 
   1633   // TODO: All unfinished verify and when statements should have sensible error messages telling
   1634   // you where the unfinished statement comes from.
   1635 
   1636   /** Returns the line number of the line following the method call. */
   1637   private int getNextLineNumber() {
   1638     return new Exception().getStackTrace()[1].getLineNumber() + 1;
   1639   }
   1640 
   1641   /** Returns a string like: "com.google.foo.TestFoo.testMethod(TestFoo:50)" */
   1642   private String singleLineStackTrace(int lineNumber) {
   1643     return getClass().getName() + "." + getName() + "(" + getClass().getSimpleName() +
   1644         ".java:" + lineNumber + ")";
   1645   }
   1646 
   1647   /** Simple callable that invokes the callback captured in the callback member variable. */
   1648   private class CallCapturedCallbackCallable implements Callable<Object> {
   1649     @Override
   1650     public Object call() {
   1651       mCaptureCallback.getValue().callMeNow();
   1652       return null;
   1653     }
   1654   }
   1655 
   1656   private Foo createNotARealMock() {
   1657     InvocationHandler handler = new InvocationHandler() {
   1658       @Override
   1659       public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   1660         return null;
   1661       }
   1662     };
   1663     Foo notARealMock = (Foo) Proxy.newProxyInstance(
   1664         getClass().getClassLoader(), new Class<?>[]{ Foo.class }, handler);
   1665     assertNotNull(notARealMock);
   1666     return notARealMock;
   1667   }
   1668 
   1669   private static Callback createNoOpCallback() {
   1670     return new Callback() {
   1671       @Override
   1672       public void callMeNow() {
   1673       }
   1674     };
   1675   }
   1676 
   1677   private static <T> List<T> newList(T... things) {
   1678     ArrayList<T> list = new ArrayList<T>();
   1679     for (T thing : things) {
   1680       list.add(thing);
   1681     }
   1682     return list;
   1683   }
   1684 }
   1685