• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito;
6 
7 import org.mockito.exceptions.misusing.PotentialStubbingProblem;
8 import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
9 import org.mockito.internal.InternalMockHandler;
10 import org.mockito.internal.MockitoCore;
11 import org.mockito.internal.creation.MockSettingsImpl;
12 import org.mockito.internal.debugging.MockitoDebuggerImpl;
13 import org.mockito.internal.framework.DefaultMockitoFramework;
14 import org.mockito.internal.session.DefaultMockitoSessionBuilder;
15 import org.mockito.internal.verification.VerificationModeFactory;
16 import org.mockito.invocation.Invocation;
17 import org.mockito.invocation.InvocationFactory;
18 import org.mockito.invocation.MockHandler;
19 import org.mockito.junit.MockitoJUnit;
20 import org.mockito.junit.MockitoJUnitRunner;
21 import org.mockito.junit.MockitoRule;
22 import org.mockito.listeners.VerificationStartedEvent;
23 import org.mockito.listeners.VerificationStartedListener;
24 import org.mockito.mock.SerializableMode;
25 import org.mockito.plugins.MockMaker;
26 import org.mockito.plugins.MockitoPlugins;
27 import org.mockito.quality.MockitoHint;
28 import org.mockito.quality.Strictness;
29 import org.mockito.session.MockitoSessionBuilder;
30 import org.mockito.session.MockitoSessionLogger;
31 import org.mockito.stubbing.Answer;
32 import org.mockito.stubbing.Answer1;
33 import org.mockito.stubbing.LenientStubber;
34 import org.mockito.stubbing.OngoingStubbing;
35 import org.mockito.stubbing.Stubber;
36 import org.mockito.stubbing.Stubbing;
37 import org.mockito.stubbing.VoidAnswer1;
38 import org.mockito.verification.After;
39 import org.mockito.verification.Timeout;
40 import org.mockito.verification.VerificationAfterDelay;
41 import org.mockito.verification.VerificationMode;
42 import org.mockito.verification.VerificationWithTimeout;
43 
44 /**
45  * <p align="left"><img src="logo.png" srcset="logo@2x.png 2x" alt="Mockito logo"/></p>
46  * The Mockito library enables mock creation, verification and stubbing.
47  *
48  * <p>
49  * This javadoc content is also available on the <a href="http://mockito.org">http://mockito.org</a> web page.
50  * All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code.
51  * It allows access to documentation straight from the IDE even if you work offline.
52  * It motivates Mockito developers to keep documentation up-to-date with the code that they write,
53  * every day, with every commit.
54  *
55  * <h1>Contents</h1>
56  *
57  * <b>
58  *      <a href="#0">0. Migrating to Mockito 2</a><br/>
59  *      <a href="#0.1">0.1 Mockito Android support</a></br/>
60  *      <a href="#0.2">0.2 Configuration-free inline mock making</a></br/>
61  *      <a href="#1">1. Let's verify some behaviour! </a><br/>
62  *      <a href="#2">2. How about some stubbing? </a><br/>
63  *      <a href="#3">3. Argument matchers </a><br/>
64  *      <a href="#4">4. Verifying exact number of invocations / at least once / never </a><br/>
65  *      <a href="#5">5. Stubbing void methods with exceptions </a><br/>
66  *      <a href="#6">6. Verification in order </a><br/>
67  *      <a href="#7">7. Making sure interaction(s) never happened on mock </a><br/>
68  *      <a href="#8">8. Finding redundant invocations </a><br/>
69  *      <a href="#9">9. Shorthand for mocks creation - <code>&#064;Mock</code> annotation </a><br/>
70  *      <a href="#10">10. Stubbing consecutive calls (iterator-style stubbing) </a><br/>
71  *      <a href="#11">11. Stubbing with callbacks </a><br/>
72  *      <a href="#12">12. <code>doReturn()</code>|<code>doThrow()</code>|<code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a><br/>
73  *      <a href="#13">13. Spying on real objects </a><br/>
74  *      <a href="#14">14. Changing default return values of unstubbed invocations (Since 1.7) </a><br/>
75  *      <a href="#15">15. Capturing arguments for further assertions (Since 1.8.0) </a><br/>
76  *      <a href="#16">16. Real partial mocks (Since 1.8.0) </a><br/>
77  *      <a href="#17">17. Resetting mocks (Since 1.8.0) </a><br/>
78  *      <a href="#18">18. Troubleshooting & validating framework usage (Since 1.8.0) </a><br/>
79  *      <a href="#19">19. Aliases for behavior driven development (Since 1.8.0) </a><br/>
80  *      <a href="#20">20. Serializable mocks (Since 1.8.1) </a><br/>
81  *      <a href="#21">21. New annotations: <code>&#064;Captor</code>, <code>&#064;Spy</code>, <code>&#064;InjectMocks</code> (Since 1.8.3) </a><br/>
82  *      <a href="#22">22. Verification with timeout (Since 1.8.5) </a><br/>
83  *      <a href="#23">23. Automatic instantiation of <code>&#064;Spies</code>, <code>&#064;InjectMocks</code> and constructor injection goodness (Since 1.9.0)</a><br/>
84  *      <a href="#24">24. One-liner stubs (Since 1.9.0)</a><br/>
85  *      <a href="#25">25. Verification ignoring stubs (Since 1.9.0)</a><br/>
86  *      <a href="#26">26. Mocking details (Improved in 2.2.x)</a><br/>
87  *      <a href="#27">27. Delegate calls to real instance (Since 1.9.5)</a><br/>
88  *      <a href="#28">28. <code>MockMaker</code> API (Since 1.9.5)</a><br/>
89  *      <a href="#29">29. BDD style verification (Since 1.10.0)</a><br/>
90  *      <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a><br/>
91  *      <a href="#31">31. Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3><br/>
92  *      <a href="#32">32. Better generic support with deep stubs (Since 1.10.0)</a></h3><br/>
93  *      <a href="#33">33. Mockito JUnit rule (Since 1.10.17)</a><br/>
94  *      <a href="#34">34. Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a><br/>
95  *      <a href="#35">35. Custom verification failure message (Since 2.1.0)</a><br/>
96  *      <a href="#36">36. Java 8 Lambda Matcher Support (Since 2.1.0)</a><br/>
97  *      <a href="#37">37. Java 8 Custom Answer Support (Since 2.1.0)</a><br/>
98  *      <a href="#38">38. Meta data and generic type retention (Since 2.1.0)</a><br/>
99  *      <a href="#39">39. Mocking final types, enums and final methods (Since 2.1.0)</a><br/>
100  *      <a href="#40">40. Improved productivity and cleaner tests with "stricter" Mockito (Since 2.+)</a><br/>
101  *      <a href="#41">41. Advanced public API for framework integrations (Since 2.10.+)</a><br/>
102  *      <a href="#42">42. New API for integrations: listening on verification start events (Since 2.11.+)</a><br/>
103  *      <a href="#43">43. New API for integrations: <code>MockitoSession</code> is usable by testing frameworks (Since 2.15.+)</a><br/>
104  *      <a href="#44">44. Deprecated <code>org.mockito.plugins.InstantiatorProvider</code> as it was leaking internal API. it was replaced by <code>org.mockito.plugins.InstantiatorProvider2 (Since 2.15.4)</code></a><br/>
105  *      <a href="#45">45. New JUnit Jupiter (JUnit5+) extension</a><br/>
106  *      <a href="#46">46. New <code>Mockito.lenient()</code> and <code>MockSettings.lenient()</code> methods (Since 2.20.0)</a><br/>
107  *      <a href="#47">47. New API for clearing mock state in inline mocking (Since 2.25.0)</a><br/>
108  * </b>
109  *
110  * <h3 id="0">0. <a class="meaningful_link" href="#mockito2" name="mockito2">Migrating to Mockito 2</a></h3>
111  *
112  * In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0!
113  * Mockito follows <a href="http://semver.org/">semantic versioning</a> and contains breaking changes only on major version upgrades.
114  * In the lifecycle of a library, breaking changes are necessary
115  * to roll out a set of brand new features that alter the existing behavior or even change the API.
116  * For a comprehensive guide on the new release including incompatible changes,
117  * see '<a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2">What's new in Mockito 2</a>' wiki page.
118  * We hope that you enjoy Mockito 2!
119  *
120  * <h3 id="0.1">0.1. <a class="meaningful_link" href="#mockito-android" name="mockito-android">Mockito Android support</a></h3>
121  *
122  * With Mockito version 2.6.1 we ship "native" Android support. To enable Android support, add the `mockito-android` library as dependency
123  * to your project. This artifact is published to the same Mockito organization and can be imported for Android as follows:
124  *
125  * <pre class="code"><code>
126  * repositories {
127  *   jcenter()
128  * }
129  * dependencies {
130  *   testCompile "org.mockito:mockito-core:+"
131  *   androidTestCompile "org.mockito:mockito-android:+"
132  * }
133  * </code></pre>
134  *
135  * You can continue to run the same unit tests on a regular VM by using the `mockito-core` artifact in your "testCompile" scope as shown
136  * above. Be aware that you cannot use the <a href="#39">inline mock maker</a> on Android due to limitations in the Android VM.
137  *
138  * If you encounter issues with mocking on Android, please open an issue
139  * <a href="https://github.com/mockito/mockito/issues/new">on the official issue tracker</a>.
140  * Do provide the version of Android you are working on and dependencies of your project.
141  *
142  * <h3 id="0.2">0.2. <a class="meaningful_link" href="#mockito-inline" name="mockito-inline">Configuration-free inline mock making</a></h3>
143  *
144  * Starting with version 2.7.6, we offer the 'mockito-inline' artifact that enables <a href="#39">inline mock making</a> without configuring
145  * the MockMaker extension file. To use this, add the `mockito-inline` instead of the `mockito-core` artifact as follows:
146  *
147  * <pre class="code"><code>
148  * repositories {
149  *   jcenter()
150  * }
151  * dependencies {
152  *   testCompile "org.mockito:mockito-inline:+"
153  * }
154  * </code></pre>
155  *
156  * Be aware that this artifact may be abolished when the inline mock making feature is integrated into the default mock maker.
157  *
158  * <p>
159  * For more information about inline mock making, see <a href="#39">section 39</a>.
160  *
161  * <h3 id="1">1. <a class="meaningful_link" href="#verification" name="verification">Let's verify some behaviour!</a></h3>
162  *
163  * The following examples mock a List, because most people are familiar with the interface (such as the
164  * <code>add()</code>, <code>get()</code>, <code>clear()</code> methods). <br>
165  * In reality, please don't mock the List class. Use a real instance instead.
166  *
167  * <pre class="code"><code class="java">
168  * //Let's import Mockito statically so that the code looks clearer
169  * import static org.mockito.Mockito.*;
170  *
171  * //mock creation
172  * List mockedList = mock(List.class);
173  *
174  * //using mock object
175  * mockedList.add("one");
176  * mockedList.clear();
177  *
178  * //verification
179  * verify(mockedList).add("one");
180  * verify(mockedList).clear();
181  * </code></pre>
182  *
183  * <p>
184  * Once created, a mock will remember all interactions. Then you can selectively
185  * verify whatever interactions you are interested in.
186  * </p>
187  *
188  *
189  *
190  * <h3 id="2">2. <a class="meaningful_link" href="#stubbing" name="stubbing">How about some stubbing?</a></h3>
191  *
192  * <pre class="code"><code class="java">
193  * //You can mock concrete classes, not just interfaces
194  * LinkedList mockedList = mock(LinkedList.class);
195  *
196  * //stubbing
197  * when(mockedList.get(0)).thenReturn("first");
198  * when(mockedList.get(1)).thenThrow(new RuntimeException());
199  *
200  * //following prints "first"
201  * System.out.println(mockedList.get(0));
202  *
203  * //following throws runtime exception
204  * System.out.println(mockedList.get(1));
205  *
206  * //following prints "null" because get(999) was not stubbed
207  * System.out.println(mockedList.get(999));
208  *
209  * //Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>
210  * //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
211  * //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
212  * verify(mockedList).get(0);
213  * </code></pre>
214  *
215  * <ul>
216  * <li> By default, for all methods that return a value, a mock will return either null,
217  * a primitive/primitive wrapper value, or an empty collection, as appropriate.
218  * For example 0 for an int/Integer and false for a boolean/Boolean. </li>
219  *
220  * <li> Stubbing can be overridden: for example common stubbing can go to
221  * fixture setup but the test methods can override it.
222  * Please note that overridding stubbing is a potential code smell that points out too much stubbing</li>
223  *
224  * <li> Once stubbed, the method will always return a stubbed value, regardless
225  * of how many times it is called. </li>
226  *
227  * <li> Last stubbing is more important - when you stubbed the same method with
228  * the same arguments many times.
229  * Other words: <b>the order of stubbing matters</b> but it is only meaningful rarely,
230  * e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.</li>
231  *
232  * </ul>
233  *
234  *
235  *
236  * <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers" name="argument_matchers">Argument matchers</a></h3>
237  *
238  * Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
239  * Sometimes, when extra flexibility is required then you might use argument matchers:
240  *
241  * <pre class="code"><code class="java">
242  * //stubbing using built-in anyInt() argument matcher
243  * when(mockedList.get(anyInt())).thenReturn("element");
244  *
245  * //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
246  * when(mockedList.contains(argThat(isValid()))).thenReturn("element");
247  *
248  * //following prints "element"
249  * System.out.println(mockedList.get(999));
250  *
251  * //<b>you can also verify using an argument matcher</b>
252  * verify(mockedList).get(anyInt());
253  *
254  * //<b>argument matchers can also be written as Java 8 Lambdas</b>
255  * verify(mockedList).add(argThat(someString -> someString.length() > 5));
256  *
257  * </code></pre>
258  *
259  * <p>
260  * Argument matchers allow flexible verification or stubbing.
261  * {@link ArgumentMatchers Click here} {@link org.mockito.hamcrest.MockitoHamcrest or here} to see more built-in matchers
262  * and examples of <b>custom argument matchers / hamcrest matchers</b>.
263  * <p>
264  * For information solely on <b>custom argument matchers</b> check out javadoc for {@link ArgumentMatcher} class.
265  * <p>
266  * Be reasonable with using complicated argument matching.
267  * The natural matching style using <code>equals()</code> with occasional <code>anyX()</code> matchers tend to give clean & simple tests.
268  * Sometimes it's just better to refactor the code to allow <code>equals()</code> matching or even implement <code>equals()</code> method to help out with testing.
269  * <p>
270  * Also, read <a href="#15">section 15</a> or javadoc for {@link ArgumentCaptor} class.
271  * {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions.
272  * <p>
273  * <b>Warning on argument matchers:</b>
274  * <p>
275  * If you are using argument matchers, <b>all arguments</b> have to be provided
276  * by matchers.
277  * <p>
278  The following example shows verification but the same applies to stubbing:
279  *
280  * <pre class="code"><code class="java">
281  *   verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
282  *   //above is correct - eq() is also an argument matcher
283  *
284  *   verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
285  *   //above is incorrect - exception will be thrown because third argument is given without an argument matcher.
286  * </code></pre>
287  *
288  * <p>
289  * Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers.
290  * Internally, they record a matcher on a stack and return a dummy value (usually null).
291  * This implementation is due to static type safety imposed by the java compiler.
292  * The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
293  *
294  *
295  *
296  *
297  * <h3 id="4">4. <a class="meaningful_link" href="#exact_verification" name="exact_verification">Verifying exact number of invocations</a> /
298  * <a class="meaningful_link" href="#at_least_verification" name="at_least_verification">at least x</a> / never</h3>
299  *
300  * <pre class="code"><code class="java">
301  * //using mock
302  * mockedList.add("once");
303  *
304  * mockedList.add("twice");
305  * mockedList.add("twice");
306  *
307  * mockedList.add("three times");
308  * mockedList.add("three times");
309  * mockedList.add("three times");
310  *
311  * //following two verifications work exactly the same - times(1) is used by default
312  * verify(mockedList).add("once");
313  * verify(mockedList, times(1)).add("once");
314  *
315  * //exact number of invocations verification
316  * verify(mockedList, times(2)).add("twice");
317  * verify(mockedList, times(3)).add("three times");
318  *
319  * //verification using never(). never() is an alias to times(0)
320  * verify(mockedList, never()).add("never happened");
321  *
322  * //verification using atLeast()/atMost()
323  * verify(mockedList, atLeastOnce()).add("three times");
324  * verify(mockedList, atLeast(2)).add("three times");
325  * verify(mockedList, atMost(5)).add("three times");
326  *
327  * </code></pre>
328  *
329  * <p>
330  * <b>times(1) is the default.</b> Therefore using times(1) explicitly can be
331  * omitted.
332  *
333  *
334  *
335  *
336  * <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions" name="stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3>
337  *
338  * <pre class="code"><code class="java">
339  *   doThrow(new RuntimeException()).when(mockedList).clear();
340  *
341  *   //following throws RuntimeException:
342  *   mockedList.clear();
343  * </code></pre>
344  *
345  * Read more about <code>doThrow()</code>|<code>doAnswer()</code> family of methods in <a href="#12">section 12</a>.
346  * <p>
347  *
348  * <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification" name="in_order_verification">Verification in order</a></h3>
349  *
350  * <pre class="code"><code class="java">
351  * // A. Single mock whose methods must be invoked in a particular order
352  * List singleMock = mock(List.class);
353  *
354  * //using a single mock
355  * singleMock.add("was added first");
356  * singleMock.add("was added second");
357  *
358  * //create an inOrder verifier for a single mock
359  * InOrder inOrder = inOrder(singleMock);
360  *
361  * //following will make sure that add is first called with "was added first, then with "was added second"
362  * inOrder.verify(singleMock).add("was added first");
363  * inOrder.verify(singleMock).add("was added second");
364  *
365  * // B. Multiple mocks that must be used in a particular order
366  * List firstMock = mock(List.class);
367  * List secondMock = mock(List.class);
368  *
369  * //using mocks
370  * firstMock.add("was called first");
371  * secondMock.add("was called second");
372  *
373  * //create inOrder object passing any mocks that need to be verified in order
374  * InOrder inOrder = inOrder(firstMock, secondMock);
375  *
376  * //following will make sure that firstMock was called before secondMock
377  * inOrder.verify(firstMock).add("was called first");
378  * inOrder.verify(secondMock).add("was called second");
379  *
380  * // Oh, and A + B can be mixed together at will
381  * </code></pre>
382  *
383  * Verification in order is flexible - <b>you don't have to verify all
384  * interactions</b> one-by-one but only those that you are interested in
385  * testing in order.
386  * <p>
387  * Also, you can create an InOrder object passing only the mocks that are relevant for
388  * in-order verification.
389  *
390  *
391  *
392  *
393  * <h3 id="7">7. <a class="meaningful_link" href="#never_verification" name="never_verification">Making sure interaction(s) never happened on mock</a></h3>
394  *
395  * <pre class="code"><code class="java">
396  * //using mocks - only mockOne is interacted
397  * mockOne.add("one");
398  *
399  * //ordinary verification
400  * verify(mockOne).add("one");
401  *
402  * //verify that method was never called on a mock
403  * verify(mockOne, never()).add("two");
404  *
405  * //verify that other mocks were not interacted
406  * verifyZeroInteractions(mockTwo, mockThree);
407  *
408  * </code></pre>
409  *
410  *
411  *
412  *
413  * <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations" name="finding_redundant_invocations">Finding redundant invocations</a></h3>
414  *
415  * <pre class="code"><code class="java">
416  * //using mocks
417  * mockedList.add("one");
418  * mockedList.add("two");
419  *
420  * verify(mockedList).add("one");
421  *
422  * //following verification will fail
423  * verifyNoMoreInteractions(mockedList);
424  * </code></pre>
425  *
426  * A word of <b>warning</b>:
427  * Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
428  * <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
429  * <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
430  * Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests. You can find further reading
431  * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
432  *
433  * <p>
434  * See also {@link Mockito#never()} - it is more explicit and
435  * communicates the intent well.
436  * <p>
437  *
438  *
439  *
440  *
441  * <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation" name="mock_annotation">Shorthand for mocks creation - <code>&#064;Mock</code> annotation</a></h3>
442  *
443  * <ul>
444  * <li>Minimizes repetitive mock creation code.</li>
445  * <li>Makes the test class more readable.</li>
446  * <li>Makes the verification error easier to read because the <b>field name</b>
447  * is used to identify the mock.</li>
448  * </ul>
449  *
450  * <pre class="code"><code class="java">
451  *   public class ArticleManagerTest {
452  *
453  *       &#064;Mock private ArticleCalculator calculator;
454  *       &#064;Mock private ArticleDatabase database;
455  *       &#064;Mock private UserProvider userProvider;
456  *
457  *       private ArticleManager manager;
458  * </code></pre>
459  *
460  * <b>Important!</b> This needs to be somewhere in the base class or a test
461  * runner:
462  *
463  * <pre class="code"><code class="java">
464  * MockitoAnnotations.initMocks(testClass);
465  * </code></pre>
466  *
467  * You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}.
468  * <p>
469  * Read more here: {@link MockitoAnnotations}
470  *
471  *
472  *
473  *
474  * <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls" name="stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3>
475  *
476  * Sometimes we need to stub with different return value/exception for the same
477  * method call. Typical use case could be mocking iterators.
478  * Original version of Mockito did not have this feature to promote simple mocking.
479  * For example, instead of iterators one could use {@link Iterable} or simply
480  * collections. Those offer natural ways of stubbing (e.g. using real
481  * collections). In rare scenarios stubbing consecutive calls could be useful,
482  * though:
483  * <p>
484  *
485  * <pre class="code"><code class="java">
486  * when(mock.someMethod("some arg"))
487  *   .thenThrow(new RuntimeException())
488  *   .thenReturn("foo");
489  *
490  * //First call: throws runtime exception:
491  * mock.someMethod("some arg");
492  *
493  * //Second call: prints "foo"
494  * System.out.println(mock.someMethod("some arg"));
495  *
496  * //Any consecutive call: prints "foo" as well (last stubbing wins).
497  * System.out.println(mock.someMethod("some arg"));
498  * </code></pre>
499  *
500  * Alternative, shorter version of consecutive stubbing:
501  *
502  * <pre class="code"><code class="java">
503  * when(mock.someMethod("some arg"))
504  *   .thenReturn("one", "two", "three");
505  * </code></pre>
506  *
507  * <strong>Warning</strong> : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with the same matchers or arguments
508  * is used, then each stubbing will override the previous one:
509  *
510  * <pre class="code"><code class="java">
511  * //All mock.someMethod("some arg") calls will return "two"
512  * when(mock.someMethod("some arg"))
513  *   .thenReturn("one")
514  * when(mock.someMethod("some arg"))
515  *   .thenReturn("two")
516  * </code></pre>
517  *
518  *
519  *
520  * <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs" name="answer_stubs">Stubbing with callbacks</a></h3>
521  *
522  * Allows stubbing with generic {@link Answer} interface.
523  * <p>
524  * Yet another controversial feature which was not included in Mockito
525  * originally. We recommend simply stubbing with <code>thenReturn()</code> or
526  * <code>thenThrow()</code>, which should be enough to test/test-drive
527  * any clean & simple code. However, if you do have a need to stub with the generic Answer interface, here is an example:
528  *
529  * <pre class="code"><code class="java">
530  * when(mock.someMethod(anyString())).thenAnswer(
531  *     new Answer() {
532  *         public Object answer(InvocationOnMock invocation) {
533  *             Object[] args = invocation.getArguments();
534  *             Object mock = invocation.getMock();
535  *             return "called with arguments: " + Arrays.toString(args);
536  *         }
537  * });
538  *
539  * //Following prints "called with arguments: [foo]"
540  * System.out.println(mock.someMethod("foo"));
541  * </code></pre>
542  *
543  *
544  *
545  *
546  * <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs" name="do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>|
547  * <code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a></h3>
548  *
549  * Stubbing void methods requires a different approach from {@link Mockito#when(Object)} because the compiler does not
550  * like void methods inside brackets...
551  * <p>
552  * Use <code>doThrow()</code> when you want to stub a void method with an exception:
553  * <pre class="code"><code class="java">
554  *   doThrow(new RuntimeException()).when(mockedList).clear();
555  *
556  *   //following throws RuntimeException:
557  *   mockedList.clear();
558  * </code></pre>
559  * </p>
560  *
561  * <p>
562  * You can use <code>doThrow()</code>, <code>doAnswer()</code>, <code>doNothing()</code>, <code>doReturn()</code>
563  * and <code>doCallRealMethod()</code> in place of the corresponding call with <code>when()</code>, for any method.
564  * It is necessary when you
565  * <ul>
566  *     <li>stub void methods</li>
567  *     <li>stub methods on spy objects (see below)</li>
568  *     <li>stub the same method more than once, to change the behaviour of a mock in the middle of a test.</li>
569  * </ul>
570  * but you may prefer to use these methods in place of the alternative with <code>when()</code>, for all of your stubbing calls.
571  * <p>
572  * Read more about these methods:
573  * <p>
574  * {@link Mockito#doReturn(Object)}
575  * <p>
576  * {@link Mockito#doThrow(Throwable...)}
577  * <p>
578  * {@link Mockito#doThrow(Class)}
579  * <p>
580  * {@link Mockito#doAnswer(Answer)}
581  * <p>
582  * {@link Mockito#doNothing()}
583  * <p>
584  * {@link Mockito#doCallRealMethod()}
585  *
586  *
587  *
588  *
589  * <h3 id="13">13. <a class="meaningful_link" href="#spy" name="spy">Spying on real objects</a></h3>
590  *
591  * You can create spies of real objects. When you use the spy then the <b>real</b> methods are called
592  * (unless a method was stubbed).
593  * <p>
594  * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
595  *
596  * <p>
597  * Spying on real objects can be associated with "partial mocking" concept.
598  * <b>Before the release 1.8</b>, Mockito spies were not real partial mocks.
599  * The reason was we thought partial mock is a code smell.
600  * At some point we found legitimate use cases for partial mocks
601  * (3rd party interfaces, interim refactoring of legacy code, the full article is
602  * <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>)
603  * <p>
604  *
605  * <pre class="code"><code class="java">
606  *   List list = new LinkedList();
607  *   List spy = spy(list);
608  *
609  *   //optionally, you can stub out some methods:
610  *   when(spy.size()).thenReturn(100);
611  *
612  *   //using the spy calls <b>*real*</b> methods
613  *   spy.add("one");
614  *   spy.add("two");
615  *
616  *   //prints "one" - the first element of a list
617  *   System.out.println(spy.get(0));
618  *
619  *   //size() method was stubbed - 100 is printed
620  *   System.out.println(spy.size());
621  *
622  *   //optionally, you can verify
623  *   verify(spy).add("one");
624  *   verify(spy).add("two");
625  * </code></pre>
626  *
627  * <h4>Important gotcha on spying real objects!</h4>
628  * <ol>
629  * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
630  * Therefore when using spies please consider <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code> family of
631  * methods for stubbing. Example:
632  *
633  * <pre class="code"><code class="java">
634  *   List list = new LinkedList();
635  *   List spy = spy(list);
636  *
637  *   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
638  *   when(spy.get(0)).thenReturn("foo");
639  *
640  *   //You have to use doReturn() for stubbing
641  *   doReturn("foo").when(spy).get(0);
642  * </code></pre>
643  * </li>
644  *
645  * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
646  * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
647  * and their effect on real instance state.
648  * The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
649  * you won't see any effects on the real instance.
650  * </li>
651  *
652  * <li>Watch out for final methods.
653  * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
654  * Also you won't be able to verify those method as well.
655  * </li>
656  * </ol>
657  *
658  *
659  *
660  *
661  * <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn" name="defaultreturn">default return values of unstubbed invocations</a> (Since 1.7)</h3>
662  *
663  * You can create a mock with specified strategy for its return values.
664  * It's quite an advanced feature and typically you don't need it to write decent tests.
665  * However, it can be helpful for working with <b>legacy systems</b>.
666  * <p>
667  * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
668  *
669  * <pre class="code"><code class="java">
670  *   Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
671  *   Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
672  * </code></pre>
673  *
674  * <p>
675  * Read more about this interesting implementation of <i>Answer</i>: {@link Mockito#RETURNS_SMART_NULLS}
676  *
677  *
678  *
679  *
680  * <h3 id="15">15. <a class="meaningful_link" href="#captors" name="captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3>
681  *
682  * Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
683  * This is also the recommended way of matching arguments because it makes tests clean & simple.
684  * In some situations though, it is helpful to assert on certain arguments after the actual verification.
685  * For example:
686  * <pre class="code"><code class="java">
687  *   ArgumentCaptor&lt;Person&gt; argument = ArgumentCaptor.forClass(Person.class);
688  *   verify(mock).doSomething(argument.capture());
689  *   assertEquals("John", argument.getValue().getName());
690  * </code></pre>
691  *
692  * <b>Warning:</b> it is recommended to use ArgumentCaptor with verification <b>but not</b> with stubbing.
693  * Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block.
694  * Also it may reduce defect localization because if stubbed method was not called then no argument is captured.
695  * <p>
696  * In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class).
697  * Both techniques can be used for making sure certain arguments where passed to mocks.
698  * However, ArgumentCaptor may be a better fit if:
699  * <ul>
700  * <li>custom argument matcher is not likely to be reused</li>
701  * <li>you just need it to assert on argument values to complete verification</li>
702  * </ul>
703  * Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
704  *
705  *
706  *
707  *
708  * <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks" name="partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3>
709  *
710  *  Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito.
711  *  Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading:
712  *  <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>
713  *  <p>
714  *  <b>Before release 1.8</b> <code>spy()</code> was not producing real partial mocks and it was confusing for some users.
715  *  Read more about spying: <a href="#13">here</a> or in javadoc for {@link Mockito#spy(Object)} method.
716  *  <p>
717  *  <pre class="code"><code class="java">
718  *    //you can create partial mock with spy() method:
719  *    List list = spy(new LinkedList());
720  *
721  *    //you can enable partial mock capabilities selectively on mocks:
722  *    Foo mock = mock(Foo.class);
723  *    //Be sure the real implementation is 'safe'.
724  *    //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
725  *    when(mock.someMethod()).thenCallRealMethod();
726  *  </code></pre>
727  *
728  * As usual you are going to read <b>the partial mock warning</b>:
729  * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
730  * How does partial mock fit into this paradigm? Well, it just doesn't...
731  * Partial mock usually means that the complexity has been moved to a different method on the same object.
732  * In most cases, this is not the way you want to design your application.
733  * <p>
734  * However, there are rare cases when partial mocks come handy:
735  * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
736  * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
737  *
738  *
739  *
740  *
741  * <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks" name="resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3>
742  *
743  * Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
744  * Normally, you don't need to reset your mocks, just create new mocks for each test method.
745  * <p>
746  * Instead of <code>reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
747  * <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
748  * Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
749  * There are several threads about it on mockito mailing list.
750  * <p>
751  * The only reason we added <code>reset()</code> method is to
752  * make it possible to work with container-injected mocks.
753  * For more information see FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
754  * <p>
755  * <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
756  * <pre class="code"><code class="java">
757  *   List mock = mock(List.class);
758  *   when(mock.size()).thenReturn(10);
759  *   mock.add(1);
760  *
761  *   reset(mock);
762  *   //at this point the mock forgot any interactions & stubbing
763  * </code></pre>
764  *
765  *
766  *
767  *
768  * <h3 id="18">18. <a class="meaningful_link" href="#framework_validation" name="framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3>
769  *
770  * First of all, in case of any trouble, I encourage you to read the Mockito FAQ:
771  * <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
772  * <p>
773  * In case of questions you may also post to mockito mailing list:
774  * <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
775  * <p>
776  * Next, you should know that Mockito validates if you use it correctly <b>all the time</b>.
777  * However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()}
778  *
779  *
780  *
781  *
782  * <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito" name="bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3>
783  *
784  * Behavior Driven Development style of writing tests uses <b>//given //when //then</b> comments as fundamental parts of your test methods.
785  * This is exactly how we write our tests and we warmly encourage you to do so!
786  * <p>
787  * Start learning about BDD here: <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">http://en.wikipedia.org/wiki/Behavior_Driven_Development</a>
788  * <p>
789  * The problem is that current stubbing api with canonical role of <b>when</b> word does not integrate nicely with <b>//given //when //then</b> comments.
790  * It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test.
791  * Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method.
792  * Now it really nicely integrates with the <b>given</b> component of a BDD style test!
793  * <p>
794  * Here is how the test might look like:
795  * <pre class="code"><code class="java">
796  * import static org.mockito.BDDMockito.*;
797  *
798  * Seller seller = mock(Seller.class);
799  * Shop shop = new Shop(seller);
800  *
801  * public void shouldBuyBread() throws Exception {
802  *   //given
803  *   given(seller.askForBread()).willReturn(new Bread());
804  *
805  *   //when
806  *   Goods goods = shop.buyBread();
807  *
808  *   //then
809  *   assertThat(goods, containBread());
810  * }
811  * </code></pre>
812  *
813  *
814  *
815  *
816  * <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks" name="serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3>
817  *
818  * Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
819  * <p>
820  * WARNING: This should be rarely used in unit testing.
821  * <p>
822  * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency.  This
823  * was in a web environment and the objects from the external dependency were being serialized to pass between layers.
824  * <p>
825  * To create serializable mock use {@link MockSettings#serializable()}:
826  * <pre class="code"><code class="java">
827  *   List serializableMock = mock(List.class, withSettings().serializable());
828  * </code></pre>
829  * <p>
830  * The mock can be serialized assuming all the normal <a href='http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html'>
831  * serialization requirements</a> are met by the class.
832  * <p>
833  * Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version
834  * which accepts MockSettings. No worries, you will hardly ever use it.
835  *
836  * <pre class="code"><code class="java">
837  * List&lt;Object&gt; list = new ArrayList&lt;Object&gt;();
838  * List&lt;Object&gt; spy = mock(ArrayList.class, withSettings()
839  *                 .spiedInstance(list)
840  *                 .defaultAnswer(CALLS_REAL_METHODS)
841  *                 .serializable());
842  * </code></pre>
843  *
844  *
845  *
846  *
847  * <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation" name="captor_annotation"><code>&#064;Captor</code></a>,
848  * <a class="meaningful_link" href="#spy_annotation" name="spy_annotation"><code>&#064;Spy</code></a>,
849  * <a class="meaningful_link" href="#injectmocks_annotation" name="injectmocks_annotation"><code>&#064;InjectMocks</code></a> (Since 1.8.3)</h3>
850  *
851  * <p>
852  * Release 1.8.3 brings new annotations that may be helpful on occasion:
853  *
854  * <ul>
855  * <li>&#064;{@link Captor} simplifies creation of {@link ArgumentCaptor}
856  * - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings
857  * <li>&#064;{@link Spy} - you can use it instead {@link Mockito#spy(Object)}.
858  * <li>&#064;{@link InjectMocks} - injects mock or spy fields into tested object automatically.
859  * </ul>
860  *
861  * <p>
862  * Note that &#064;{@link InjectMocks} can also be used in combination with the &#064;{@link Spy} annotation, it means
863  * that Mockito will inject mocks into the partial mock under test. This complexity is another good reason why you
864  * should only use partial mocks as a last resort. See point 16 about partial mocks.
865  *
866  * <p>
867  * All new annotations are <b>*only*</b> processed on {@link MockitoAnnotations#initMocks(Object)}.
868  * Just like for &#064;{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule:
869  * {@link MockitoRule}.
870  * <p>
871  *
872  *
873  *
874  *
875  * <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout" name="verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3>
876  * <p>
877  * Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired
878  * interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent
879  * conditions.
880  * <p>
881  * This feature should be used rarely - figure out a better way of testing your multi-threaded system.
882  * <p>
883  * Not yet implemented to work with InOrder verification.
884  * <p>
885  * Examples:
886  * <p>
887  * <pre class="code"><code class="java">
888  *   //passes when someMethod() is called no later than within 100 ms
889  *   //exits immediately when verification is satisfied (e.g. may not wait full 100 ms)
890  *   verify(mock, timeout(100)).someMethod();
891  *   //above is an alias to:
892  *   verify(mock, timeout(100).times(1)).someMethod();
893  *
894  *   //passes as soon as someMethod() has been called 2 times under 100 ms
895  *   verify(mock, timeout(100).times(2)).someMethod();
896  *
897  *   //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms
898  *   verify(mock, timeout(100).atLeast(2)).someMethod();
899  * </code></pre>
900  *
901  *
902  *
903  *
904  * <h3 id="23">23. <a class="meaningful_link" href="#automatic_instantiation" name="automatic_instantiation">Automatic instantiation of <code>&#064;Spies</code>,
905  * <code>&#064;InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection" name="constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3>
906  *
907  * <p>
908  * Mockito will now try to instantiate &#064;{@link Spy} and will instantiate &#064;{@link InjectMocks} fields
909  * using <b>constructor</b> injection, <b>setter</b> injection, or <b>field</b> injection.
910  * <p>
911  * To take advantage of this feature you need to use {@link MockitoAnnotations#initMocks(Object)}, {@link MockitoJUnitRunner}
912  * or {@link MockitoRule}.
913  * <p>
914  * Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks}
915  * <pre class="code"><code class="java">
916  * //instead:
917  * &#064;Spy BeerDrinker drinker = new BeerDrinker();
918  * //you can write:
919  * &#064;Spy BeerDrinker drinker;
920  *
921  * //same applies to &#064;InjectMocks annotation:
922  * &#064;InjectMocks LocalPub;
923  * </code></pre>
924  *
925  *
926  *
927  *
928  * <h3 id="24">24. <a class="meaningful_link" href="#one_liner_stub" name="one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3>
929  * <p>
930  * Mockito will now allow you to create mocks when stubbing.
931  * Basically, it allows to create a stub in one line of code.
932  * This can be helpful to keep test code clean.
933  * For example, some boring stub can be created & stubbed at field initialization in a test:
934  * <pre class="code"><code class="java">
935  * public class CarTest {
936  *   Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
937  *
938  *   &#064;Test public void should... {}
939  * </code></pre>
940  *
941  *
942  *
943  *
944  * <h3 id="25">25. <a class="meaningful_link" href="#ignore_stubs_verification" name="ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3>
945  * <p>
946  * Mockito will now allow to ignore stubbing for the sake of verification.
947  * Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
948  * Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
949  * <p>
950  * <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...));
951  * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
952  * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
953  * <p>Some examples:
954  * <pre class="code"><code class="java">
955  * verify(mock).foo();
956  * verify(mockTwo).bar();
957  *
958  * //ignores all stubbed methods:
959  * verifyNoMoreInteractions(ignoreStubs(mock, mockTwo));
960  *
961  * //creates InOrder that will ignore stubbed
962  * InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));
963  * inOrder.verify(mock).foo();
964  * inOrder.verify(mockTwo).bar();
965  * inOrder.verifyNoMoreInteractions();
966  * </code></pre>
967  * <p>
968  * Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)}
969  *
970  *
971  *
972  *
973  * <h3 id="26">26. <a class="meaningful_link" href="#mocking_details" name="mocking_details">Mocking details</a> (Improved in 2.2.x)</h3>
974  * <p>
975  *
976  * Mockito offers API to inspect the details of a mock object.
977  * This API is useful for advanced users and mocking framework integrators.
978  *
979  * <pre class="code"><code class="java">
980  *   //To identify whether a particular object is a mock or a spy:
981  *   Mockito.mockingDetails(someObject).isMock();
982  *   Mockito.mockingDetails(someObject).isSpy();
983  *
984  *   //Getting details like type to mock or default answer:
985  *   MockingDetails details = mockingDetails(mock);
986  *   details.getMockCreationSettings().getTypeToMock();
987  *   details.getMockCreationSettings().getDefaultAnswer();
988  *
989  *   //Getting invocations and stubbings of the mock:
990  *   MockingDetails details = mockingDetails(mock);
991  *   details.getInvocations();
992  *   details.getStubbings();
993  *
994  *   //Printing all interactions (including stubbing, unused stubs)
995  *   System.out.println(mockingDetails(mock).printInvocations());
996  * </code></pre>
997  *
998  * For more information see javadoc for {@link MockingDetails}.
999  *
1000  * <h3 id="27">27. <a class="meaningful_link" href="#delegating_call_to_real_instance" name="delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3>
1001  *
1002  * <p>Useful for spies or partial mocks of objects <strong>that are difficult to mock or spy</strong> using the usual spy API.
1003  * Since Mockito 1.10.11, the delegate may or may not be of the same type as the mock.
1004  * If the type is different, a matching method needs to be found on delegate type otherwise an exception is thrown.
1005  *
1006  * Possible use cases for this feature:
1007  * <ul>
1008  *     <li>Final classes but with an interface</li>
1009  *     <li>Already custom proxied object</li>
1010  *     <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li>
1011  * </ul>
1012  *
1013  * <p>The difference with the regular spy:
1014  * <ul>
1015  *   <li>
1016  *     The regular spy ({@link #spy(Object)}) contains <strong>all</strong> state from the spied instance
1017  *     and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from.
1018  *     If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered
1019  *     for verifications, and they can be effectively stubbed.
1020  *   </li>
1021  *   <li>
1022  *     The mock that delegates simply delegates all methods to the delegate.
1023  *     The delegate is used all the time as methods are delegated onto it.
1024  *     If you call a method on a mock that delegates and it internally calls other methods on this mock,
1025  *     those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too.
1026  *     Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created.
1027  *   </li>
1028  * </ul>
1029  *
1030  * <p>
1031  * See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}.
1032  *
1033  *
1034  *
1035  *
1036  * <h3 id="28">28. <a class="meaningful_link" href="#mock_maker_plugin" name="mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3>
1037  * <p>Driven by requirements and patches from Google Android guys Mockito now offers an extension point
1038  *   that allows replacing the proxy generation engine. By default, Mockito uses <a href="https://github.com/raphw/byte-buddy">Byte Buddy</a>
1039  *   to create dynamic proxies.
1040  * <p>The extension point is for advanced users that want to extend Mockito. For example, it is now possible
1041  *   to use Mockito for Android testing with a help of <a href="https://github.com/crittercism/dexmaker">dexmaker</a>.
1042  * <p>For more details, motivations and examples please refer to
1043  * the docs for {@link org.mockito.plugins.MockMaker}.
1044  *
1045  *
1046  *
1047  *
1048  * <h3 id="29">29. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">BDD style verification</a> (Since 1.10.0)</h3>
1049  *
1050  * Enables Behavior Driven Development (BDD) style verification by starting verification with the BDD <b>then</b> keyword.
1051  *
1052  * <pre class="code"><code class="java">
1053  * given(dog.bark()).willReturn(2);
1054  *
1055  * // when
1056  * ...
1057  *
1058  * then(person).should(times(2)).ride(bike);
1059  * </code></pre>
1060  *
1061  * For more information and an example see {@link BDDMockito#then(Object)}
1062  *
1063  *
1064  *
1065  *
1066  * <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes" name="spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a></h3>
1067  *
1068  * It is now possible to conveniently spy on abstract classes. Note that overusing spies hints at code design smells (see {@link #spy(Object)}).
1069  * <p>
1070  * Previously, spying was only possible on instances of objects.
1071  * New API makes it possible to use constructor when creating an instance of the mock.
1072  * This is particularly useful for mocking abstract classes because the user is no longer required to provide an instance of the abstract class.
1073  * At the moment, only parameter-less constructor is supported, let us know if it is not enough.
1074  *
1075  * <pre class="code"><code class="java">
1076  * //convenience API, new overloaded spy() method:
1077  * SomeAbstract spy = spy(SomeAbstract.class);
1078  *
1079  * //Mocking abstract methods, spying default methods of an interface (only available since 2.7.13)
1080  * Function<Foo, Bar> function = spy(Function.class);
1081  *
1082  * //Robust API, via settings builder:
1083  * OtherAbstract spy = mock(OtherAbstract.class, withSettings()
1084  *    .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
1085  *
1086  * //Mocking an abstract class with constructor arguments (only available since 2.7.14)
1087  * SomeAbstract spy = mock(SomeAbstract.class, withSettings()
1088  *   .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS));
1089  *
1090  * //Mocking a non-static inner abstract class:
1091  * InnerAbstract spy = mock(InnerAbstract.class, withSettings()
1092  *    .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
1093  * </code></pre>
1094  *
1095  * For more information please see {@link MockSettings#useConstructor(Object...)}.
1096  *
1097  *
1098  *
1099  *
1100  * <h3 id="31">31. <a class="meaningful_link" href="#serilization_across_classloader" name="serilization_across_classloader">Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3>
1101  *
1102  * Mockito introduces serialization across classloader.
1103  *
1104  * Like with any other form of serialization, all types in the mock hierarchy have to serializable, inclusing answers.
1105  * As this serialization mode require considerably more work, this is an opt-in setting.
1106  *
1107  * <pre class="code"><code class="java">
1108  * // use regular serialization
1109  * mock(Book.class, withSettings().serializable());
1110  *
1111  * // use serialization across classloaders
1112  * mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));
1113  * </code></pre>
1114  *
1115  * For more details see {@link MockSettings#serializable(SerializableMode)}.
1116  *
1117  *
1118  *
1119  *
1120  * <h3 id="32">32. <a class="meaningful_link" href="#better_generic_support_with_deep_stubs" name="better_generic_support_with_deep_stubs">Better generic support with deep stubs (Since 1.10.0)</a></h3>
1121  *
1122  * Deep stubbing has been improved to find generic information if available in the class.
1123  * That means that classes like this can be used without having to mock the behavior.
1124  *
1125  * <pre class="code"><code class="java">
1126  * class Lines extends List&lt;Line&gt; {
1127  *     // ...
1128  * }
1129  *
1130  * lines = mock(Lines.class, RETURNS_DEEP_STUBS);
1131  *
1132  * // Now Mockito understand this is not an Object but a Line
1133  * Line line = lines.iterator().next();
1134  * </code></pre>
1135  *
1136  * Please note that in most scenarios a mock returning a mock is wrong.
1137  *
1138  *
1139  *
1140  *
1141  * <h3 id="33">33. <a class="meaningful_link" href="#mockito_junit_rule" name="mockito_junit_rule">Mockito JUnit rule (Since 1.10.17)</a></h3>
1142  *
1143  * Mockito now offers a JUnit rule. Until now in JUnit there were two ways to initialize fields annotated by Mockito annotations
1144  * such as <code>&#064;{@link Mock}</code>, <code>&#064;{@link Spy}</code>, <code>&#064;{@link InjectMocks}</code>, etc.
1145  *
1146  * <ul>
1147  *     <li>Annotating the JUnit test class with a <code>&#064;{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)</code></li>
1148  *     <li>Invoking <code>{@link MockitoAnnotations#initMocks(Object)}</code> in the <code>&#064;{@link org.junit.Before}</code> method</li>
1149  * </ul>
1150  *
1151  * Now you can choose to use a rule :
1152  *
1153  * <pre class="code"><code class="java">
1154  * &#064;RunWith(YetAnotherRunner.class)
1155  * public class TheTest {
1156  *     &#064;Rule public MockitoRule mockito = MockitoJUnit.rule();
1157  *     // ...
1158  * }
1159  * </code></pre>
1160  *
1161  * For more information see {@link MockitoJUnit#rule()}.
1162  *
1163  *
1164  *
1165  *
1166  * <h3 id="34">34. <a class="meaningful_link" href="#plugin_switch" name="plugin_switch">Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a></h3>
1167  *
1168  * An incubating feature made it's way in mockito that will allow to toggle a mockito-plugin.
1169  *
1170  * More information here {@link org.mockito.plugins.PluginSwitch}.
1171  *
1172  *
1173  * <h3 id="35">35. <a class="meaningful_link" href="#Custom_verification_failure_message" name="Custom_verification_failure_message">Custom verification failure message</a> (Since 2.1.0)</h3>
1174  * <p>
1175  * Allows specifying a custom message to be printed if verification fails.
1176  * <p>
1177  * Examples:
1178  * <p>
1179  * <pre class="code"><code class="java">
1180  *
1181  * // will print a custom message on verification failure
1182  * verify(mock, description("This will print on failure")).someMethod();
1183  *
1184  * // will work with any verification mode
1185  * verify(mock, times(2).description("someMethod should be called twice")).someMethod();
1186  * </code></pre>
1187  *
1188  * <h3 id="36">36. <a class="meaningful_link" href="#Java_8_Lambda_Matching" name="Java_8_Lambda_Matching">Java 8 Lambda Matcher Support</a> (Since 2.1.0)</h3>
1189  * <p>
1190  * You can use Java 8 lambda expressions with {@link ArgumentMatcher} to reduce the dependency on {@link ArgumentCaptor}.
1191  * If you need to verify that the input to a function call on a mock was correct, then you would normally
1192  * use the {@link ArgumentCaptor} to find the operands used and then do subsequent assertions on them. While
1193  * for complex examples this can be useful, it's also long-winded.<p>
1194  * Writing a lambda to express the match is quite easy. The argument to your function, when used in conjunction
1195  * with argThat, will be passed to the ArgumentMatcher as a strongly typed object, so it is possible
1196  * to do anything with it.
1197  * <p>
1198  * Examples:
1199  * <p>
1200  * <pre class="code"><code class="java">
1201  *
1202  * // verify a list only had strings of a certain length added to it
1203  * // note - this will only compile under Java 8
1204  * verify(list, times(2)).add(argThat(string -> string.length() < 5));
1205  *
1206  * // Java 7 equivalent - not as neat
1207  * verify(list, times(2)).add(argThat(new ArgumentMatcher<String>(){
1208  *     public boolean matches(String arg) {
1209  *         return arg.length() < 5;
1210  *     }
1211  * }));
1212  *
1213  * // more complex Java 8 example - where you can specify complex verification behaviour functionally
1214  * verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));
1215  *
1216  * // this can also be used when defining the behaviour of a mock under different inputs
1217  * // in this case if the input list was fewer than 3 items the mock returns null
1218  * when(mock.someMethod(argThat(list -> list.size()<3))).thenReturn(null);
1219  * </code></pre>
1220  *
1221  * <h3 id="37">37. <a class="meaningful_link" href="#Java_8_Custom_Answers" name="Java_8_Custom_Answers">Java 8 Custom Answer Support</a> (Since 2.1.0)</h3>
1222  * <p>
1223  * As the {@link Answer} interface has just one method it is already possible to implement it in Java 8 using
1224  * a lambda expression for very simple situations. The more you need to use the parameters of the method call,
1225  * the more you need to typecast the arguments from {@link org.mockito.invocation.InvocationOnMock}.
1226  *
1227  * <p>
1228  * Examples:
1229  * <p>
1230  * <pre class="code"><code class="java">
1231  * // answer by returning 12 every time
1232  * doAnswer(invocation -> 12).when(mock).doSomething();
1233  *
1234  * // answer by using one of the parameters - converting into the right
1235  * // type as your go - in this case, returning the length of the second string parameter
1236  * // as the answer. This gets long-winded quickly, with casting of parameters.
1237  * doAnswer(invocation -> ((String)invocation.getArgument(1)).length())
1238  *     .when(mock).doSomething(anyString(), anyString(), anyString());
1239  * </code></pre>
1240  *
1241  * For convenience it is possible to write custom answers/actions, which use the parameters to the method call,
1242  * as Java 8 lambdas. Even in Java 7 and lower these custom answers based on a typed interface can reduce boilerplate.
1243  * In particular, this approach will make it easier to test functions which use callbacks.
1244  *
1245  * The methods {@link AdditionalAnswers#answer(Answer1) answer} and {@link AdditionalAnswers#answerVoid(VoidAnswer1) answerVoid}
1246  * can be used to create the answer. They rely on the related answer interfaces in {@link org.mockito.stubbing} that
1247  * support answers up to 5 parameters.
1248  *
1249  * <p>
1250  * Examples:
1251  * <p>
1252  * <pre class="code"><code class="java">
1253  *
1254  * // Example interface to be mocked has a function like:
1255  * void execute(String operand, Callback callback);
1256  *
1257  * // the example callback has a function and the class under test
1258  * // will depend on the callback being invoked
1259  * void receive(String item);
1260  *
1261  * // Java 8 - style 1
1262  * doAnswer(AdditionalAnswers.<String,Callback>answerVoid((operand, callback) -> callback.receive("dummy"))
1263  *     .when(mock).execute(anyString(), any(Callback.class));
1264  *
1265  * // Java 8 - style 2 - assuming static import of AdditionalAnswers
1266  * doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))
1267  *     .when(mock).execute(anyString(), any(Callback.class));
1268  *
1269  * // Java 8 - style 3 - where mocking function to is a static member of test class
1270  * private static void dummyCallbackImpl(String operation, Callback callback) {
1271  *     callback.receive("dummy");
1272  * }
1273  *
1274  * doAnswer(answerVoid(TestClass::dummyCallbackImpl)
1275  *     .when(mock).execute(anyString(), any(Callback.class));
1276  *
1277  * // Java 7
1278  * doAnswer(answerVoid(new VoidAnswer2<String, Callback>() {
1279  *     public void answer(String operation, Callback callback) {
1280  *         callback.receive("dummy");
1281  *     }})).when(mock).execute(anyString(), any(Callback.class));
1282  *
1283  * // returning a value is possible with the answer() function
1284  * // and the non-void version of the functional interfaces
1285  * // so if the mock interface had a method like
1286  * boolean isSameString(String input1, String input2);
1287  *
1288  * // this could be mocked
1289  * // Java 8
1290  * doAnswer(AdditionalAnswers.<Boolean,String,String>answer((input1, input2) -> input1.equals(input2))))
1291  *     .when(mock).execute(anyString(), anyString());
1292  *
1293  * // Java 7
1294  * doAnswer(answer(new Answer2<String, String, String>() {
1295  *     public String answer(String input1, String input2) {
1296  *         return input1 + input2;
1297  *     }})).when(mock).execute(anyString(), anyString());
1298  * </code></pre>
1299  *
1300  * <h3 id="38">38. <a class="meaningful_link" href="#Meta_Data_And_Generics" name="Meta_Data_And_Generics">Meta data and generic type retention</a> (Since 2.1.0)</h3>
1301  *
1302  * <p>
1303  * Mockito now preserves annotations on mocked methods and types as well as generic meta data. Previously, a mock type did not preserve
1304  * annotations on types unless they were explicitly inherited and never retained annotations on methods. As a consequence, the following
1305  * conditions now hold true:
1306  *
1307  * <pre class="code"><code class="java">
1308  * {@literal @}{@code MyAnnotation
1309  *  class Foo {
1310  *    List<String> bar() { ... }
1311  *  }
1312  *
1313  *  Class<?> mockType = mock(Foo.class).getClass();
1314  *  assert mockType.isAnnotationPresent(MyAnnotation.class);
1315  *  assert mockType.getDeclaredMethod("bar").getGenericReturnType() instanceof ParameterizedType;
1316  * }</code></pre>
1317  *
1318  * <p>
1319  * When using Java 8, Mockito now also preserves type annotations. This is default behavior and might not hold <a href="#28">if an
1320  * alternative {@link org.mockito.plugins.MockMaker} is used</a>.
1321  *
1322  * <h3 id="39">39. <a class="meaningful_link" href="#Mocking_Final" name="Mocking_Final">Mocking final types, enums and final methods</a> (Since 2.1.0)</h3>
1323  *
1324  * Mockito now offers an {@link Incubating}, optional support for mocking final classes and methods.
1325  * This is a fantastic improvement that demonstrates Mockito's everlasting quest for improving testing experience.
1326  * Our ambition is that Mockito "just works" with final classes and methods.
1327  * Previously they were considered <em>unmockable</em>, preventing the user from mocking.
1328  * We already started discussing how to make this feature enabled by default.
1329  * Currently, the feature is still optional as we wait for more feedback from the community.
1330  *
1331  * <p>
1332  * This alternative mock maker which uses
1333  * a combination of both Java instrumentation API and sub-classing rather than creating a new class to represent
1334  * a mock. This way, it becomes possible to mock final types and methods.
1335  *
1336  * <p>
1337  * This mock maker is <strong>turned off by default</strong> because it is based on completely different mocking mechanism
1338  * that requires more feedback from the community. It can be activated explicitly by the mockito extension mechanism,
1339  * just create in the classpath a file <code>/mockito-extensions/org.mockito.plugins.MockMaker</code>
1340  * containing the value <code>mock-maker-inline</code>.
1341  *
1342  * <p>
1343  * As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the
1344  * <i>mockito-core</i> artifact, include the <i>mockito-inline</i> artifact in your project. Note that this artifact is
1345  * likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker.
1346  *
1347  * <p>
1348  * Some noteworthy notes about this mock maker:
1349  * <ul>
1350  *     <li>Mocking final types and enums is incompatible with mock settings like :
1351  *     <ul>
1352  *         <li>explicitly serialization support <code>withSettings().serializable()</code></li>
1353  *         <li>extra-interfaces <code>withSettings().extraInterfaces()</code></li>
1354  *     </ul>
1355  *     </li>
1356  *     <li>Some methods cannot be mocked
1357  *         <ul>
1358  *              <li>Package-visible methods of <code>java.*</code></li>
1359  *              <li><code>native</code> methods</li>
1360  *         </ul>
1361  *     </li>
1362  *     <li>This mock maker has been designed around Java Agent runtime attachment ; this require a compatible JVM,
1363  *     that is part of the JDK (or Java 9 VM). When running on a non-JDK VM prior to Java 9, it is however possible to
1364  *     manually add the <a href="http://bytebuddy.net">Byte Buddy Java agent jar</a> using the <code>-javaagent</code>
1365  *     parameter upon starting the JVM.
1366  *     </li>
1367  * </ul>
1368  *
1369  * <p>
1370  * If you are interested in more details of this feature please read the javadoc of
1371  * <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code>
1372  *
1373  * <h3 id="40">40. <a class="meaningful_link" href="#strict_mockito" name="strict_mockito">
1374  *     Improved productivity and cleaner tests with "stricter" Mockito</a> (Since 2.+)</h3>
1375  *
1376  * To quickly find out how "stricter" Mockito can make you more productive and get your tests cleaner, see:
1377  * <ul>
1378  *     <li>Strict stubbing with JUnit Rules - {@link MockitoRule#strictness(Strictness)} with {@link Strictness#STRICT_STUBS}</li>
1379  *     <li>Strict stubbing with JUnit Runner - {@link MockitoJUnitRunner.StrictStubs}</li>
1380  *     <li>Strict stubbing if you cannot use runner/rule (like TestNG) - {@link MockitoSession}</li>
1381  *     <li>Unnecessary stubbing detection with {@link MockitoJUnitRunner}</li>
1382  *     <li>Stubbing argument mismatch warnings, documented in {@link MockitoHint}</li>
1383  * </ul>
1384  *
1385  * Mockito is a "loose" mocking framework by default.
1386  * Mocks can be interacted with without setting any expectations beforehand.
1387  * This is intentional and it improves the quality of tests by forcing users to be explicit about what they want to stub / verify.
1388  * It is also very intuitive, easy to use and blends nicely with "given", "when", "then" template of clean test code.
1389  * This is also different from the classic mocking frameworks of the past, they were "strict" by default.
1390  * <p>
1391  * Being "loose" by default makes Mockito tests harder to debug at times.
1392  * There are scenarios where misconfigured stubbing (like using a wrong argument) forces the user to run the test with a debugger.
1393  * Ideally, tests failures are immediately obvious and don't require debugger to identify the root cause.
1394  * Starting with version 2.1 Mockito has been getting new features that nudge the framework towards "strictness".
1395  * We want Mockito to offer fantastic debuggability while not losing its core mocking style, optimized for
1396  * intuitiveness, explicitness and clean test code.
1397  * <p>
1398  * Help Mockito! Try the new features, give us feedback, join the discussion about Mockito strictness at GitHub
1399  * <a href="https://github.com/mockito/mockito/issues/769">issue 769</a>.
1400  *
1401  * <h3 id="41">41. <a class="meaningful_link" href="#framework_integrations_api" name="framework_integrations_api">
1402  *      Advanced public API for framework integrations (Since 2.10.+)</a></h3>
1403  *
1404  * In Summer 2017 we decided that Mockito
1405  * <a href="https://www.linkedin.com/pulse/mockito-vs-powermock-opinionated-dogmatic-static-mocking-faber">
1406  * should offer better API
1407  * </a>
1408  * for advanced framework integrations.
1409  * The new API is not intended for users who want to write unit tests.
1410  * It is intended for other test tools and mocking frameworks that need to extend or wrap Mockito with some custom logic.
1411  * During the design and implementation process (<a href="https://github.com/mockito/mockito/issues/1110">issue 1110</a>)
1412  * we have developed and changed following public API elements:
1413  * <ul>
1414  *     <li>New {@link MockitoPlugins} -
1415  *      Enables framework integrators to get access to default Mockito plugins.
1416  *      Useful when one needs to implement custom plugin such as {@link MockMaker}
1417  *      and delegate some behavior to the default Mockito implementation.
1418  *     </li>
1419  *     <li>New {@link MockSettings#build(Class)} -
1420  *      Creates immutable view of mock settings used later by Mockito.
1421  *      Useful for creating invocations with {@link InvocationFactory} or when implementing custom {@link MockHandler}.
1422  *     </li>
1423  *     <li>New {@link MockingDetails#getMockHandler()} -
1424  *      Other frameworks may use the mock handler to programmatically simulate invocations on mock objects.
1425  *     </li>
1426  *     <li>New {@link MockHandler#getMockSettings()} -
1427  *      Useful to get hold of the setting the mock object was created with.
1428  *     </li>
1429  *     <li>New {@link InvocationFactory} -
1430  *      Provides means to create instances of {@link Invocation} objects.
1431  *      Useful for framework integrations that need to programmatically simulate method calls on mock objects.
1432  *     </li>
1433  *     <li>New {@link MockHandler#getInvocationContainer()} -
1434  *      Provides access to invocation container object which has no methods (marker interface).
1435  *      Container is needed to hide the internal implementation and avoid leaking it to the public API.
1436  *     </li>
1437  *     <li>Changed {@link Stubbing} -
1438  *      it now extends {@link Answer} interface.
1439  *      It is backwards compatible because Stubbing interface is not extensible (see {@link NotExtensible}).
1440  *      The change should be seamless to our users.
1441  *     </li>
1442  *     <li>Deprecated {@link InternalMockHandler} -
1443  *       In order to accommodate API changes we needed to deprecate this interface.
1444  *       The interface was always documented as internal, we don't have evidence it was used by the community.
1445  *       The deprecation should be completely seamless for our users.
1446  *     </li>
1447  *     <li>{@link NotExtensible} -
1448  *       Public annotation that indicates to the user that she should not provide custom implementations of given type.
1449  *       Helps framework integrators and our users understand how to use Mockito API safely.
1450  *     </li>
1451  * </ul>
1452  * Do you have feedback? Please leave comment in <a href="https://github.com/mockito/mockito/issues/1110">issue 1110</a>.
1453  *
1454  * <h3 id="42">42. <a class="meaningful_link" href="#verifiation_started_listener" name="verifiation_started_listener">
1455  *       New API for integrations: listening on verification start events (Since 2.11.+)</a></h3>
1456  *
1457  * Framework integrations such as <a href="https://projects.spring.io/spring-boot">Spring Boot</a> needs public API to tackle double-proxy use case
1458  * (<a href="https://github.com/mockito/mockito/issues/1191">issue 1191</a>).
1459  * We added:
1460  * <ul>
1461  *     <li>New {@link VerificationStartedListener} and {@link VerificationStartedEvent}
1462  *      enable framework integrators to replace the mock object for verification.
1463  *      The main driving use case is <a href="https://projects.spring.io/spring-boot/">Spring Boot</a> integration.
1464  *      For details see Javadoc for {@link VerificationStartedListener}.
1465  *     </li>
1466  *     <li>New public method {@link MockSettings#verificationStartedListeners(VerificationStartedListener...)}
1467  *     allows to supply verification started listeners at mock creation time.
1468  *     </li>
1469  *     <li>New handy method {@link MockingDetails#getMock()} was added to make the {@code MockingDetails} API more complete.
1470  *     We found this method useful during the implementation.
1471  *     </li>
1472  * </ul>
1473  *
1474  * <h3 id="43">43. <a class="meaningful_link" href="#mockito_session_testing_frameworks" name="mockito_session_testing_frameworks">
1475  *       New API for integrations: <code>MockitoSession</code> is usable by testing frameworks (Since 2.15.+)</a></h3>
1476  *
1477  * <p>{@link MockitoSessionBuilder} and {@link MockitoSession} were enhanced to enable reuse by testing framework
1478  * integrations (e.g. {@link MockitoRule} for JUnit):</p>
1479  * <ul>
1480  *     <li>{@link MockitoSessionBuilder#initMocks(Object...)} allows to pass in multiple test class instances for
1481  *      initialization of fields annotated with Mockito annotations like {@link org.mockito.Mock}.
1482  *      This method is useful for advanced framework integrations (e.g. JUnit Jupiter), when a test uses multiple,
1483  *      e.g. nested, test class instances.
1484  *     </li>
1485  *     <li>{@link MockitoSessionBuilder#name(String)} allows to pass a name from the testing framework to the
1486  *      {@link MockitoSession} that will be used for printing warnings when {@link Strictness#WARN} is used.
1487  *     </li>
1488  *     <li>{@link MockitoSessionBuilder#logger(MockitoSessionLogger)} makes it possible to customize the logger used
1489  *      for hints/warnings produced when finishing mocking (useful for testing and to connect reporting capabilities
1490  *      provided by testing frameworks such as JUnit Jupiter).
1491  *     </li>
1492  *     <li>{@link MockitoSession#setStrictness(Strictness)} allows to change the strictness of a {@link MockitoSession}
1493  *      for one-off scenarios, e.g. it enables configuring a default strictness for all tests in a class but makes it
1494  *      possible to change the strictness for a single or a few tests.
1495  *     </li>
1496  *     <li>{@link MockitoSession#finishMocking(Throwable)} was added to avoid confusion that may arise because
1497  *      there are multiple competing failures. It will disable certain checks when the supplied <em>failure</em>
1498  *      is not {@code null}.
1499  *     </li>
1500  * </ul>
1501  *
1502  * <h3 id="44">44. <a class="meaningful_link" href="#mockito_instantiator_provider_deprecation" name="mockito_instantiator_provider_deprecation">
1503  *       Deprecated <code>org.mockito.plugins.InstantiatorProvider</code> as it was leaking internal API. it was
1504  *       replaced by <code>org.mockito.plugins.InstantiatorProvider2 (Since 2.15.4)</a></h3>
1505  *
1506  * <p>{@link org.mockito.plugins.InstantiatorProvider} returned an internal API. Hence it was deprecated and replaced
1507  * by {@link org.mockito.plugins.InstantiatorProvider2}. Old {@link org.mockito.plugins.InstantiatorProvider
1508  * instantiator providers} will continue to work, but it is recommended to switch to the new API.</p>
1509  *
1510  * <h3 id="45">45. <a class="meaningful_link" href="#junit5_mockito" name="junit5_mockito">New JUnit Jupiter (JUnit5+) extension</a></h3>
1511  *
1512  * For integration with JUnit Jupiter (JUnit5+), use the `org.mockito:mockito-junit-jupiter` artifact.
1513  * For more information about the usage of the integration, see <a href="http://javadoc.io/page/org.mockito/mockito-junit-jupiter/latest/org/mockito/junit/jupiter/MockitoExtension.html">the JavaDoc of <code>MockitoExtension</code></a>.
1514  *
1515  * <h3 id="46">46. <a class="meaningful_link" href="#mockito_lenient" name="mockito_lenient">
1516  *       New <code>Mockito.lenient()</code> and <code>MockSettings.lenient()</code> methods (Since 2.20.0)</a></h3>
1517  *
1518  * Strict stubbing feature is available since early Mockito 2.
1519  * It is very useful because it drives cleaner tests and improved productivity.
1520  * Strict stubbing reports unnecessary stubs, detects stubbing argument mismatch and makes the tests more DRY ({@link Strictness#STRICT_STUBS}).
1521  * This comes with a trade-off: in some cases, you may get false negatives from strict stubbing.
1522  * To remedy those scenarios you can now configure specific stubbing to be lenient, while all the other stubbings and mocks use strict stubbing:
1523  *
1524  * <pre class="code"><code class="java">
1525  *   lenient().when(mock.foo()).thenReturn("ok");
1526  * </code></pre>
1527  *
1528  * If you want all the stubbings on a given mock to be lenient, you can configure the mock accordingly:
1529  *
1530  * <pre class="code"><code class="java">
1531  *   Foo mock = Mockito.mock(Foo.class, withSettings().lenient());
1532  * </code></pre>
1533  *
1534  * For more information refer to {@link Mockito#lenient()}.
1535  * Let us know how do you find the new feature by opening a GitHub issue to discuss!
1536  *
1537  * <h3 id="47">47. <a class="meaningful_link" href="#clear_inline_mocks" name="clear_inline_mocks">New API for clearing mock state in inline mocking (Since 2.25.0)</a></h3>
1538  *
1539  * In certain specific, rare scenarios (issue <a href="https://github.com/mockito/mockito/pull/1619">#1619</a>)
1540  * inline mocking causes memory leaks.
1541  * There is no clean way to mitigate this problem completely.
1542  * Hence, we introduced a new API to explicitly clear mock state (only make sense in inline mocking!).
1543  * See example usage in {@link MockitoFramework#clearInlineMocks()}.
1544  * If you have feedback or a better idea how to solve the problem please reach out.
1545  */
1546 @SuppressWarnings("unchecked")
1547 public class Mockito extends ArgumentMatchers {
1548 
1549     static final MockitoCore MOCKITO_CORE = new MockitoCore();
1550 
1551     /**
1552      * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
1553      *
1554      * Typically it just returns some empty value.
1555      * <p>
1556      * {@link Answer} can be used to define the return values of unstubbed invocations.
1557      * <p>
1558      * This implementation first tries the global configuration and if there is no global configuration then
1559      * it will use a default answer that returns zeros, empty collections, nulls, etc.
1560      */
1561     public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;
1562 
1563     /**
1564      * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
1565      * <p>
1566      * {@link Answer} can be used to define the return values of unstubbed invocations.
1567      * <p>
1568      * This implementation can be helpful when working with legacy code.
1569      * Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.
1570      * This implementation of Answer <b>returns SmartNull instead of null</b>.
1571      * <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
1572      * <p>
1573      * <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)
1574      * then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.
1575      * <p>
1576      * <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 3.0.0
1577      * <p>
1578      * Example:
1579      * <pre class="code"><code class="java">
1580      *   Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
1581      *
1582      *   //calling unstubbed method here:
1583      *   Stuff stuff = mock.getStuff();
1584      *
1585      *   //using object returned by unstubbed call:
1586      *   stuff.doSomething();
1587      *
1588      *   //Above doesn't yield NullPointerException this time!
1589      *   //Instead, SmartNullPointerException is thrown.
1590      *   //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.
1591      * </code></pre>
1592      */
1593     public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;
1594 
1595     /**
1596      * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
1597      * <p>
1598      * {@link Answer} can be used to define the return values of unstubbed invocations.
1599      * <p>
1600      * This implementation can be helpful when working with legacy code.
1601      * <p>
1602      * ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)
1603      * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.
1604      * <p>
1605      */
1606     public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;
1607 
1608     /**
1609      * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
1610      * <p>
1611      * Example that shows how deep stub works:
1612      * <pre class="code"><code class="java">
1613      *   Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
1614      *
1615      *   // note that we're stubbing a chain of methods here: getBar().getName()
1616      *   when(mock.getBar().getName()).thenReturn("deep");
1617      *
1618      *   // note that we're chaining method calls: getBar().getName()
1619      *   assertEquals("deep", mock.getBar().getName());
1620      * </code></pre>
1621      * </p>
1622      *
1623      * <p>
1624      * <strong>WARNING: </strong>
1625      * This feature should rarely be required for regular clean code! Leave it for legacy code.
1626      * Mocking a mock to return a mock, to return a mock, (...), to return something meaningful
1627      * hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
1628      * </p>
1629      *
1630      * <p>
1631      * Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.
1632      * </p>
1633      *
1634      * <p>
1635      * Please note that this answer will return existing mocks that matches the stub. This
1636      * behavior is ok with deep stubs and allows verification to work on the last mock of the chain.
1637      * <pre class="code"><code class="java">
1638      *   when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep");
1639      *
1640      *   mock.getBar("candy bar").getThingy().getName();
1641      *
1642      *   assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName());
1643      *   verify(mock.getBar("candy bar").getThingy()).getName();
1644      *   verify(mock.getBar(anyString()).getThingy()).getName();
1645      * </code></pre>
1646      * </p>
1647      *
1648      * <p>
1649      * Verification only works with the last mock in the chain. You can use verification modes.
1650      * <pre class="code"><code class="java">
1651      *   when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
1652      *   when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");
1653      *   when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");
1654      *
1655      *   person.getAddress("the docks").getStreet().getName();
1656      *   person.getAddress("the docks").getStreet().getLongName();
1657      *   person.getAddress("the docks").getStreet(Locale.ITALIAN).getName();
1658      *   person.getAddress("the docks").getStreet(Locale.CHINESE).getName();
1659      *
1660      *   // note that we are actually referring to the very last mock in the stubbing chain.
1661      *   InOrder inOrder = inOrder(
1662      *       person.getAddress("the docks").getStreet(),
1663      *       person.getAddress("the docks").getStreet(Locale.CHINESE),
1664      *       person.getAddress("the docks").getStreet(Locale.ITALIAN)
1665      *   );
1666      *   inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();
1667      *   inOrder.verify(person.getAddress("the docks").getStreet()).getLongName();
1668      *   inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();
1669      *   inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();
1670      * </code></pre>
1671      * </p>
1672      *
1673      * <p>
1674      * How deep stub work internally?
1675      * <pre class="code"><code class="java">
1676      *   //this:
1677      *   Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
1678      *   when(mock.getBar().getName(), "deep");
1679      *
1680      *   //is equivalent of
1681      *   Foo foo = mock(Foo.class);
1682      *   Bar bar = mock(Bar.class);
1683      *   when(foo.getBar()).thenReturn(bar);
1684      *   when(bar.getName()).thenReturn("deep");
1685      * </code></pre>
1686      * </p>
1687      *
1688      * <p>
1689      * This feature will not work when any return type of methods included in the chain cannot be mocked
1690      * (for example: is a primitive or a final class). This is because of java type system.
1691      * </p>
1692      */
1693     public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;
1694 
1695     /**
1696      * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
1697      * <p>
1698      * {@link Answer} can be used to define the return values of unstubbed invocations.
1699      * <p>
1700      * This implementation can be helpful when working with legacy code.
1701      * When this implementation is used, unstubbed methods will delegate to the real implementation.
1702      * This is a way to create a partial mock object that calls real methods by default.
1703      * <p>
1704      * As usual you are going to read <b>the partial mock warning</b>:
1705      * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
1706      * How does partial mock fit into this paradigm? Well, it just doesn't...
1707      * Partial mock usually means that the complexity has been moved to a different method on the same object.
1708      * In most cases, this is not the way you want to design your application.
1709      * <p>
1710      * However, there are rare cases when partial mocks come handy:
1711      * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
1712      * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
1713      * <p>
1714      * Example:
1715      * <pre class="code"><code class="java">
1716      * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
1717      *
1718      * // this calls the real implementation of Foo.getSomething()
1719      * value = mock.getSomething();
1720      *
1721      * doReturn(fakeValue).when(mock).getSomething();
1722      *
1723      * // now fakeValue is returned
1724      * value = mock.getSomething();
1725      * </code></pre>
1726      *
1727      * <p>
1728      * <u>Note:</u> Stubbing partial mocks using <code>when(mock.getSomething()).thenReturn(fakeValue)</code>
1729      * syntax will call the real method. For partial mock it's recommended to use <code>doReturn</code> syntax.
1730      */
1731     public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;
1732 
1733     /**
1734      * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
1735      *
1736      * Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal
1737      * to the class or a superclass.
1738      *
1739      * <p><b>Keep in mind this answer uses the return type of a method.
1740      * If this type is assignable to the class of the mock, it will return the mock.
1741      * Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p>
1742      *
1743      * Consider a HttpBuilder used in a HttpRequesterWithHeaders.
1744      *
1745      * <pre class="code"><code class="java">
1746      * public class HttpRequesterWithHeaders {
1747      *
1748      *      private HttpBuilder builder;
1749      *
1750      *      public HttpRequesterWithHeaders(HttpBuilder builder) {
1751      *          this.builder = builder;
1752      *      }
1753      *
1754      *      public String request(String uri) {
1755      *          return builder.withUrl(uri)
1756      *                  .withHeader("Content-type: application/json")
1757      *                  .withHeader("Authorization: Bearer")
1758      *                  .request();
1759      *      }
1760      *  }
1761      *
1762      *  private static class HttpBuilder {
1763      *
1764      *      private String uri;
1765      *      private List&lt;String&gt; headers;
1766      *
1767      *      public HttpBuilder() {
1768      *          this.headers = new ArrayList&lt;String&gt;();
1769      *      }
1770      *
1771      *       public HttpBuilder withUrl(String uri) {
1772      *           this.uri = uri;
1773      *           return this;
1774      *       }
1775      *
1776      *       public HttpBuilder withHeader(String header) {
1777      *           this.headers.add(header);
1778      *           return this;
1779      *       }
1780      *
1781      *       public String request() {
1782      *          return uri + headers.toString();
1783      *       }
1784      *  }
1785      * </code></pre>
1786      *
1787      * The following test will succeed
1788      *
1789      * <pre><code>
1790      * &#064;Test
1791      *  public void use_full_builder_with_terminating_method() {
1792      *      HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);
1793      *      HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder);
1794      *      String response = "StatusCode: 200";
1795      *
1796      *      when(builder.request()).thenReturn(response);
1797      *
1798      *      assertThat(requester.request("URI")).isEqualTo(response);
1799      *  }
1800      * </code></pre>
1801      */
1802     public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;
1803 
1804     /**
1805      * Creates mock object of given class or interface.
1806      * <p>
1807      * See examples in javadoc for {@link Mockito} class
1808      *
1809      * @param classToMock class or interface to mock
1810      * @return mock object
1811      */
1812     @CheckReturnValue
mock(Class<T> classToMock)1813     public static <T> T mock(Class<T> classToMock) {
1814         return mock(classToMock, withSettings());
1815     }
1816 
1817     /**
1818      * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
1819      * <p>
1820      * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
1821      * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
1822      * <p>
1823      * <b>If you use <code>&#064;Mock</code> annotation then you've got naming mocks for free!</b> <code>&#064;Mock</code> uses field name as mock name. {@link Mock Read more.}
1824      * <p>
1825      *
1826      * See examples in javadoc for {@link Mockito} class
1827      *
1828      * @param classToMock class or interface to mock
1829      * @param name of the mock
1830      * @return mock object
1831      */
1832     @CheckReturnValue
mock(Class<T> classToMock, String name)1833     public static <T> T mock(Class<T> classToMock, String name) {
1834         return mock(classToMock, withSettings()
1835                 .name(name)
1836                 .defaultAnswer(RETURNS_DEFAULTS));
1837     }
1838 
1839     /**
1840      * Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.
1841      * Can be used to find out if given object is a Mockito mock
1842      * or to find out if a given mock is a spy or mock.
1843      * <p>
1844      * In future Mockito versions MockingDetails may grow and provide other useful information about the mock,
1845      * e.g. invocations, stubbing info, etc.
1846      *
1847      * @param toInspect - object to inspect. null input is allowed.
1848      * @return A {@link org.mockito.MockingDetails} instance.
1849      * @since 1.9.5
1850      */
1851     @CheckReturnValue
mockingDetails(Object toInspect)1852     public static MockingDetails mockingDetails(Object toInspect) {
1853         return MOCKITO_CORE.mockingDetails(toInspect);
1854     }
1855 
1856     /**
1857      * Creates mock with a specified strategy for its answers to interactions.
1858      * It's quite an advanced feature and typically you don't need it to write decent tests.
1859      * However it can be helpful when working with legacy systems.
1860      * <p>
1861      * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
1862      *
1863      * <pre class="code"><code class="java">
1864      *   Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
1865      *   Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
1866      * </code></pre>
1867      *
1868      * <p>See examples in javadoc for {@link Mockito} class</p>
1869      *
1870      * @param classToMock class or interface to mock
1871      * @param defaultAnswer default answer for unstubbed methods
1872      *
1873      * @return mock object
1874      */
1875     @CheckReturnValue
mock(Class<T> classToMock, Answer defaultAnswer)1876     public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
1877         return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
1878     }
1879 
1880     /**
1881      * Creates a mock with some non-standard settings.
1882      * <p>
1883      * The number of configuration points for a mock grows
1884      * so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.
1885      * Hence {@link MockSettings}.
1886      * <pre class="code"><code class="java">
1887      *   Listener mock = mock(Listener.class, withSettings()
1888      *     .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
1889      *   );
1890      * </code></pre>
1891      * <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?
1892      * Is the code under test so complicated that it requires non-standard mocks?
1893      * Wouldn't you prefer to refactor the code under test so it is testable in a simple way?
1894      * <p>
1895      * See also {@link Mockito#withSettings()}
1896      * <p>
1897      * See examples in javadoc for {@link Mockito} class
1898      *
1899      * @param classToMock class or interface to mock
1900      * @param mockSettings additional mock settings
1901      * @return mock object
1902      */
1903     @CheckReturnValue
mock(Class<T> classToMock, MockSettings mockSettings)1904     public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
1905         return MOCKITO_CORE.mock(classToMock, mockSettings);
1906     }
1907 
1908     /**
1909      * Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed.
1910      * <p>
1911      * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
1912      * <p>
1913      * As usual you are going to read <b>the partial mock warning</b>:
1914      * Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects.
1915      * How does partial mock fit into this paradigm? Well, it just doesn't...
1916      * Partial mock usually means that the complexity has been moved to a different method on the same object.
1917      * In most cases, this is not the way you want to design your application.
1918      * <p>
1919      * However, there are rare cases when partial mocks come handy:
1920      * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
1921      * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
1922      * <p>
1923      * Example:
1924      *
1925      * <pre class="code"><code class="java">
1926      *   List list = new LinkedList();
1927      *   List spy = spy(list);
1928      *
1929      *   //optionally, you can stub out some methods:
1930      *   when(spy.size()).thenReturn(100);
1931      *
1932      *   //using the spy calls <b>real</b> methods
1933      *   spy.add("one");
1934      *   spy.add("two");
1935      *
1936      *   //prints "one" - the first element of a list
1937      *   System.out.println(spy.get(0));
1938      *
1939      *   //size() method was stubbed - 100 is printed
1940      *   System.out.println(spy.size());
1941      *
1942      *   //optionally, you can verify
1943      *   verify(spy).add("one");
1944      *   verify(spy).add("two");
1945      * </code></pre>
1946      *
1947      * <h4>Important gotcha on spying real objects!</h4>
1948      * <ol>
1949      * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
1950      * Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>
1951      * family of methods for stubbing. Example:
1952      *
1953      * <pre class="code"><code class="java">
1954      *   List list = new LinkedList();
1955      *   List spy = spy(list);
1956      *
1957      *   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
1958      *   when(spy.get(0)).thenReturn("foo");
1959      *
1960      *   //You have to use doReturn() for stubbing
1961      *   doReturn("foo").when(spy).get(0);
1962      * </code></pre>
1963      * </li>
1964      *
1965      * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
1966      * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
1967      * and their effect on real instance state.
1968      * The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
1969      * you won't see any effects on the real instance.</li>
1970      *
1971      * <li>Watch out for final methods.
1972      * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
1973      * Also you won't be able to verify those method as well.
1974      * </li>
1975      * </ol>
1976      * <p>
1977      * See examples in javadoc for {@link Mockito} class
1978      *
1979      * <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them.
1980      * It may troublesome for code that rely on the spy to have these annotations.</p>
1981      *
1982      *
1983      * @param object
1984      *            to spy on
1985      * @return a spy of the real object
1986      */
1987     @CheckReturnValue
spy(T object)1988     public static <T> T spy(T object) {
1989         return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
1990                 .spiedInstance(object)
1991                 .defaultAnswer(CALLS_REAL_METHODS));
1992     }
1993 
1994     /**
1995      * Please refer to the documentation of {@link #spy(Object)}.
1996      * Overusing spies hints at code design smells.
1997      * <p>
1998      * This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object.
1999      * Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object.
2000      * This is particularly useful for spying on abstract classes because they cannot be instantiated.
2001      * See also {@link MockSettings#useConstructor(Object...)}.
2002      * <p>
2003      * Examples:
2004      * <pre class="code"><code class="java">
2005      *   SomeAbstract spy = spy(SomeAbstract.class);
2006      *
2007      *   //Robust API, via settings builder:
2008      *   OtherAbstract spy = mock(OtherAbstract.class, withSettings()
2009      *      .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
2010      *
2011      *   //Mocking a non-static inner abstract class:
2012      *   InnerAbstract spy = mock(InnerAbstract.class, withSettings()
2013      *      .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
2014      * </code></pre>
2015      *
2016      * @param classToSpy the class to spy
2017      * @param <T> type of the spy
2018      * @return a spy of the provided class
2019      * @since 1.10.12
2020      */
2021     @Incubating
2022     @CheckReturnValue
spy(Class<T> classToSpy)2023     public static <T> T spy(Class<T> classToSpy) {
2024         return MOCKITO_CORE.mock(classToSpy, withSettings()
2025                 .useConstructor()
2026                 .defaultAnswer(CALLS_REAL_METHODS));
2027     }
2028 
2029     /**
2030      * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.
2031      * <p>
2032      * Simply put: "<b>When</b> the x method is called <b>then</b> return y".
2033      *
2034      * <p>
2035      * Examples:
2036      *
2037      * <pre class="code"><code class="java">
2038      * <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10);
2039      *
2040      * //you can use flexible argument matchers, e.g:
2041      * when(mock.someMethod(<b>anyString()</b>)).thenReturn(10);
2042      *
2043      * //setting exception to be thrown:
2044      * when(mock.someMethod("some arg")).thenThrow(new RuntimeException());
2045      *
2046      * //you can set different behavior for consecutive method calls.
2047      * //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
2048      * when(mock.someMethod("some arg"))
2049      *  .thenThrow(new RuntimeException())
2050      *  .thenReturn("foo");
2051      *
2052      * //Alternative, shorter version for consecutive stubbing:
2053      * when(mock.someMethod("some arg"))
2054      *  .thenReturn("one", "two");
2055      * //is the same as:
2056      * when(mock.someMethod("some arg"))
2057      *  .thenReturn("one")
2058      *  .thenReturn("two");
2059      *
2060      * //shorter version for consecutive method calls throwing exceptions:
2061      * when(mock.someMethod("some arg"))
2062      *  .thenThrow(new RuntimeException(), new NullPointerException();
2063      *
2064      * </code></pre>
2065      *
2066      * For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable...)}
2067      * <p>
2068      * Stubbing can be overridden: for example common stubbing can go to fixture
2069      * setup but the test methods can override it.
2070      * Please note that overridding stubbing is a potential code smell that points out too much stubbing.
2071      * <p>
2072      * Once stubbed, the method will always return stubbed value regardless
2073      * of how many times it is called.
2074      * <p>
2075      * Last stubbing is more important - when you stubbed the same method with
2076      * the same arguments many times.
2077      * <p>
2078      * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
2079      * Let's say you've stubbed <code>foo.bar()</code>.
2080      * If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
2081      * If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
2082      * Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
2083      *
2084      * <p>
2085      * See examples in javadoc for {@link Mockito} class
2086      * @param methodCall method to be stubbed
2087      * @return OngoingStubbing object used to stub fluently.
2088      *         <strong>Do not</strong> create a reference to this returned object.
2089      */
2090     @CheckReturnValue
when(T methodCall)2091     public static <T> OngoingStubbing<T> when(T methodCall) {
2092         return MOCKITO_CORE.when(methodCall);
2093     }
2094 
2095     /**
2096      * Verifies certain behavior <b>happened once</b>.
2097      * <p>
2098      * Alias to <code>verify(mock, times(1))</code> E.g:
2099      * <pre class="code"><code class="java">
2100      *   verify(mock).someMethod("some arg");
2101      * </code></pre>
2102      * Above is equivalent to:
2103      * <pre class="code"><code class="java">
2104      *   verify(mock, times(1)).someMethod("some arg");
2105      * </code></pre>
2106      * <p>
2107      * Arguments passed are compared using <code>equals()</code> method.
2108      * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
2109      * <p>
2110      * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
2111      * Let's say you've stubbed <code>foo.bar()</code>.
2112      * If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
2113      * If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
2114      * Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
2115      *
2116      * <p>
2117      * See examples in javadoc for {@link Mockito} class
2118      *
2119      * @param mock to be verified
2120      * @return mock object itself
2121      */
2122     @CheckReturnValue
verify(T mock)2123     public static <T> T verify(T mock) {
2124         return MOCKITO_CORE.verify(mock, times(1));
2125     }
2126 
2127     /**
2128      * Verifies certain behavior happened at least once / exact number of times / never. E.g:
2129      * <pre class="code"><code class="java">
2130      *   verify(mock, times(5)).someMethod("was called five times");
2131      *
2132      *   verify(mock, atLeast(2)).someMethod("was called at least two times");
2133      *
2134      *   //you can use flexible argument matchers, e.g:
2135      *   verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>);
2136      * </code></pre>
2137      *
2138      * <b>times(1) is the default</b> and can be omitted
2139      * <p>
2140      * Arguments passed are compared using <code>equals()</code> method.
2141      * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
2142      * <p>
2143      *
2144      * @param mock to be verified
2145      * @param mode times(x), atLeastOnce() or never()
2146      *
2147      * @return mock object itself
2148      */
2149     @CheckReturnValue
verify(T mock, VerificationMode mode)2150     public static <T> T verify(T mock, VerificationMode mode) {
2151         return MOCKITO_CORE.verify(mock, mode);
2152     }
2153 
2154     /**
2155      * Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
2156      * Normally, you don't need to reset your mocks, just create new mocks for each test method.
2157      * <p>
2158      * Instead of <code>#reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
2159      * <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
2160      * Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
2161      * There are several threads about it on mockito mailing list.
2162      * <p>
2163      * The only reason we added <code>reset()</code> method is to
2164      * make it possible to work with container-injected mocks.
2165      * For more information see the FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
2166      * <p>
2167      * <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
2168      * <pre class="code"><code class="java">
2169      *   List mock = mock(List.class);
2170      *   when(mock.size()).thenReturn(10);
2171      *   mock.add(1);
2172      *
2173      *   reset(mock);
2174      *   //at this point the mock forgot any interactions & stubbing
2175      * </code></pre>
2176      *
2177      * @param <T> The Type of the mocks
2178      * @param mocks to be reset
2179      */
reset(T .... mocks)2180     public static <T> void reset(T ... mocks) {
2181         MOCKITO_CORE.reset(mocks);
2182     }
2183 
2184     /**
2185      * Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:
2186      * <ul>
2187      *     <li>You are using a dependency injection framework to inject your mocks.</li>
2188      *     <li>The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.</li>
2189      * </ul>
2190      *
2191      * <b>Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.</b>
2192      * @param <T> The type of the mocks
2193      * @param mocks The mocks to clear the invocations for
2194      */
clearInvocations(T .... mocks)2195     public static <T> void clearInvocations(T ... mocks) {
2196         MOCKITO_CORE.clearInvocations(mocks);
2197     }
2198 
2199     /**
2200      * Checks if any of given mocks has any unverified interaction.
2201      * <p>
2202      * You can use this method after you verified your mocks - to make sure that nothing
2203      * else was invoked on your mocks.
2204      * <p>
2205      * See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
2206      * <p>
2207      * Stubbed invocations (if called) are also treated as interactions.
2208      * If you want stubbed invocations automatically verified, check out {@link Strictness#STRICT_STUBS} feature
2209      * introduced in Mockito 2.3.0.
2210      * If you want to ignore stubs for verification, see {@link #ignoreStubs(Object...)}.
2211      * <p>
2212      * A word of <b>warning</b>:
2213      * Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
2214      * <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
2215      * <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
2216      * Abusing it leads to overspecified, less maintainable tests. You can find further reading
2217      * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
2218      * <p>
2219      * This method will also detect unverified invocations that occurred before the test method,
2220      * for example: in <code>setUp()</code>, <code>&#064;Before</code> method or in constructor.
2221      * Consider writing nice code that makes interactions only in test methods.
2222      *
2223      * <p>
2224      * Example:
2225      *
2226      * <pre class="code"><code class="java">
2227      * //interactions
2228      * mock.doSomething();
2229      * mock.doSomethingUnexpected();
2230      *
2231      * //verification
2232      * verify(mock).doSomething();
2233      *
2234      * //following will fail because 'doSomethingUnexpected()' is unexpected
2235      * verifyNoMoreInteractions(mock);
2236      *
2237      * </code></pre>
2238      *
2239      * See examples in javadoc for {@link Mockito} class
2240      *
2241      * @param mocks to be verified
2242      */
verifyNoMoreInteractions(Object... mocks)2243     public static void verifyNoMoreInteractions(Object... mocks) {
2244         MOCKITO_CORE.verifyNoMoreInteractions(mocks);
2245     }
2246 
2247     /**
2248      * Verifies that no interactions happened on given mocks beyond the previously verified interactions.<br/>
2249      * This method has the same behavior as {@link #verifyNoMoreInteractions(Object...)}.
2250      *
2251      * @param mocks to be verified
2252      */
verifyZeroInteractions(Object... mocks)2253     public static void verifyZeroInteractions(Object... mocks) {
2254         MOCKITO_CORE.verifyNoMoreInteractions(mocks);
2255     }
2256 
2257     /**
2258      * Use <code>doThrow()</code> when you want to stub the void method with an exception.
2259      * <p>
2260      * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
2261      * does not like void methods inside brackets...
2262      * <p>
2263      * Example:
2264      *
2265      * <pre class="code"><code class="java">
2266      *   doThrow(new RuntimeException()).when(mock).someVoidMethod();
2267      * </code></pre>
2268      *
2269      * @param toBeThrown to be thrown when the stubbed method is called
2270      * @return stubber - to select a method for stubbing
2271      */
2272     @CheckReturnValue
doThrow(Throwable... toBeThrown)2273     public static Stubber doThrow(Throwable... toBeThrown) {
2274         return MOCKITO_CORE.stubber().doThrow(toBeThrown);
2275     }
2276 
2277     /**
2278      * Use <code>doThrow()</code> when you want to stub the void method with an exception.
2279      * <p>
2280      * A new exception instance will be created for each method invocation.
2281      * <p>
2282      * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
2283      * does not like void methods inside brackets...
2284      * <p>
2285      * Example:
2286      *
2287      * <pre class="code"><code class="java">
2288      *   doThrow(RuntimeException.class).when(mock).someVoidMethod();
2289      * </code></pre>
2290      *
2291      * @param toBeThrown to be thrown when the stubbed method is called
2292      * @return stubber - to select a method for stubbing
2293      * @since 2.1.0
2294      */
2295     @CheckReturnValue
doThrow(Class<? extends Throwable> toBeThrown)2296     public static Stubber doThrow(Class<? extends Throwable> toBeThrown) {
2297         return MOCKITO_CORE.stubber().doThrow(toBeThrown);
2298     }
2299 
2300     /**
2301      * Same as {@link #doThrow(Class)} but sets consecutive exception classes to be thrown. Remember to use
2302      * <code>doThrow()</code> when you want to stub the void method to throw several exception of specified class.
2303      * <p>
2304      * A new exception instance will be created for each method invocation.
2305      * <p>
2306      * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
2307      * does not like void methods inside brackets...
2308      * <p>
2309      * Example:
2310      *
2311      * <pre class="code"><code class="java">
2312      *   doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod();
2313      * </code></pre>
2314      *
2315      * @param toBeThrown to be thrown when the stubbed method is called
2316      * @param toBeThrownNext next to be thrown when the stubbed method is called
2317      * @return stubber - to select a method for stubbing
2318      * @since 2.1.0
2319      */
2320     // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
2321     @SuppressWarnings ({"unchecked", "varargs"})
2322     @CheckReturnValue
doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext)2323     public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) {
2324         return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
2325     }
2326 
2327 
2328     /**
2329      * Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method.
2330      * <p>
2331      * As usual you are going to read <b>the partial mock warning</b>:
2332      * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
2333      * How does partial mock fit into this paradigm? Well, it just doesn't...
2334      * Partial mock usually means that the complexity has been moved to a different method on the same object.
2335      * In most cases, this is not the way you want to design your application.
2336      * <p>
2337      * However, there are rare cases when partial mocks come handy:
2338      * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
2339      * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
2340      * <p>
2341      * See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks.
2342      * <b>Mockito.spy() is a recommended way of creating partial mocks.</b>
2343      * The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
2344      * <p>
2345      * Example:
2346      * <pre class="code"><code class="java">
2347      *   Foo mock = mock(Foo.class);
2348      *   doCallRealMethod().when(mock).someVoidMethod();
2349      *
2350      *   // this will call the real implementation of Foo.someVoidMethod()
2351      *   mock.someVoidMethod();
2352      * </code></pre>
2353      * <p>
2354      * See examples in javadoc for {@link Mockito} class
2355      *
2356      * @return stubber - to select a method for stubbing
2357      * @since 1.9.5
2358      */
2359     @CheckReturnValue
doCallRealMethod()2360     public static Stubber doCallRealMethod() {
2361         return MOCKITO_CORE.stubber().doCallRealMethod();
2362     }
2363 
2364     /**
2365      * Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}.
2366      * <p>
2367      * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
2368      * <p>
2369      * Example:
2370      *
2371      * <pre class="code"><code class="java">
2372      *  doAnswer(new Answer() {
2373      *      public Object answer(InvocationOnMock invocation) {
2374      *          Object[] args = invocation.getArguments();
2375      *          Mock mock = invocation.getMock();
2376      *          return null;
2377      *      }})
2378      *  .when(mock).someMethod();
2379      * </code></pre>
2380      * <p>
2381      * See examples in javadoc for {@link Mockito} class
2382      *
2383      * @param answer to answer when the stubbed method is called
2384      * @return stubber - to select a method for stubbing
2385      */
2386     @CheckReturnValue
doAnswer(Answer answer)2387     public static Stubber doAnswer(Answer answer) {
2388         return MOCKITO_CORE.stubber().doAnswer(answer);
2389     }
2390 
2391     /**
2392      * Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b>
2393      * However, there are rare situations when doNothing() comes handy:
2394      * <p>
2395      * <ol>
2396      * <li>Stubbing consecutive calls on a void method:
2397      * <pre class="code"><code class="java">
2398      *   doNothing().
2399      *   doThrow(new RuntimeException())
2400      *   .when(mock).someVoidMethod();
2401      *
2402      *   //does nothing the first time:
2403      *   mock.someVoidMethod();
2404      *
2405      *   //throws RuntimeException the next time:
2406      *   mock.someVoidMethod();
2407      * </code></pre>
2408      * </li>
2409      * <li>When you spy real objects and you want the void method to do nothing:
2410      * <pre class="code"><code class="java">
2411      *   List list = new LinkedList();
2412      *   List spy = spy(list);
2413      *
2414      *   //let's make clear() do nothing
2415      *   doNothing().when(spy).clear();
2416      *
2417      *   spy.add("one");
2418      *
2419      *   //clear() does nothing, so the list still contains "one"
2420      *   spy.clear();
2421      * </code></pre>
2422      * </li>
2423      * </ol>
2424      * <p>
2425      * See examples in javadoc for {@link Mockito} class
2426      *
2427      * @return stubber - to select a method for stubbing
2428      */
2429     @CheckReturnValue
doNothing()2430     public static Stubber doNothing() {
2431         return MOCKITO_CORE.stubber().doNothing();
2432     }
2433 
2434     /**
2435      * Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
2436      * <p>
2437      * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
2438      * and more readable</b> (especially when stubbing consecutive calls).
2439      * <p>
2440      * Here are those rare occasions when doReturn() comes handy:
2441      * <p>
2442      *
2443      * <ol>
2444      * <li>When spying real objects and calling real methods on a spy brings side effects
2445      *
2446      * <pre class="code"><code class="java">
2447      *   List list = new LinkedList();
2448      *   List spy = spy(list);
2449      *
2450      *   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
2451      *   when(spy.get(0)).thenReturn("foo");
2452      *
2453      *   //You have to use doReturn() for stubbing:
2454      *   doReturn("foo").when(spy).get(0);
2455      * </code></pre>
2456      * </li>
2457      *
2458      * <li>Overriding a previous exception-stubbing:
2459      * <pre class="code"><code class="java">
2460      *   when(mock.foo()).thenThrow(new RuntimeException());
2461      *
2462      *   //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
2463      *   when(mock.foo()).thenReturn("bar");
2464      *
2465      *   //You have to use doReturn() for stubbing:
2466      *   doReturn("bar").when(mock).foo();
2467      * </code></pre>
2468      * </li>
2469      * </ol>
2470      *
2471      * Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though.
2472      * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
2473      * overridding stubbing is a potential code smell that points out too much stubbing.
2474      * <p>
2475      * See examples in javadoc for {@link Mockito} class
2476      *
2477      * @param toBeReturned to be returned when the stubbed method is called
2478      * @return stubber - to select a method for stubbing
2479      */
2480     @CheckReturnValue
doReturn(Object toBeReturned)2481     public static Stubber doReturn(Object toBeReturned) {
2482         return MOCKITO_CORE.stubber().doReturn(toBeReturned);
2483     }
2484 
2485     /**
2486      * Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
2487      * <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
2488      * <p>
2489      * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
2490      * and more readable</b> (especially when stubbing consecutive calls).
2491      * <p>
2492      * Here are those rare occasions when doReturn() comes handy:
2493      * <p>
2494      *
2495      * <ol>
2496      * <li>When spying real objects and calling real methods on a spy brings side effects
2497      *
2498      * <pre class="code"><code class="java">
2499      *   List list = new LinkedList();
2500      *   List spy = spy(list);
2501      *
2502      *   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
2503      *   when(spy.get(0)).thenReturn("foo", "bar", "qix");
2504      *
2505      *   //You have to use doReturn() for stubbing:
2506      *   doReturn("foo", "bar", "qix").when(spy).get(0);
2507      * </code></pre>
2508      * </li>
2509      *
2510      * <li>Overriding a previous exception-stubbing:
2511      * <pre class="code"><code class="java">
2512      *   when(mock.foo()).thenThrow(new RuntimeException());
2513      *
2514      *   //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
2515      *   when(mock.foo()).thenReturn("bar", "foo", "qix");
2516      *
2517      *   //You have to use doReturn() for stubbing:
2518      *   doReturn("bar", "foo", "qix").when(mock).foo();
2519      * </code></pre>
2520      * </li>
2521      * </ol>
2522      *
2523      * Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
2524      * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
2525      * overridding stubbing is a potential code smell that points out too much stubbing.
2526      * <p>
2527      * See examples in javadoc for {@link Mockito} class
2528      *
2529      * @param toBeReturned to be returned when the stubbed method is called
2530      * @param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
2531      * @return stubber - to select a method for stubbing
2532      * @since 2.1.0
2533      */
2534     @SuppressWarnings({"unchecked", "varargs"})
2535     @CheckReturnValue
doReturn(Object toBeReturned, Object... toBeReturnedNext)2536     public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
2537         return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
2538     }
2539 
2540     /**
2541      * Creates {@link org.mockito.InOrder} object that allows verifying mocks in order.
2542      *
2543      * <pre class="code"><code class="java">
2544      *   InOrder inOrder = inOrder(firstMock, secondMock);
2545      *
2546      *   inOrder.verify(firstMock).add("was called first");
2547      *   inOrder.verify(secondMock).add("was called second");
2548      * </code></pre>
2549      *
2550      * Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one
2551      * but only those that you are interested in testing in order.
2552      * <p>
2553      * Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
2554      * <p>
2555      * <code>InOrder</code> verification is 'greedy', but you will hardly ever notice it.
2556      * If you want to find out more, read
2557      * <a href="https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verfication-InOrder">this wiki page</a>.
2558      * <p>
2559      * As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
2560      * <p>
2561      * See examples in javadoc for {@link Mockito} class
2562      *
2563      * @param mocks to be verified in order
2564      *
2565      * @return InOrder object to be used to verify in order
2566      */
2567     @CheckReturnValue
inOrder(Object... mocks)2568     public static InOrder inOrder(Object... mocks) {
2569         return MOCKITO_CORE.inOrder(mocks);
2570     }
2571 
2572     /**
2573      * Ignores stubbed methods of given mocks for the sake of verification.
2574      * Please consider using {@link Strictness#STRICT_STUBS} feature which eliminates the need for <code>ignoreStubs()</code>
2575      * and provides other benefits.
2576      * <p>
2577      * <code>ignoreStubs()</code> is sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
2578      * Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
2579      * <p>
2580      * <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code>
2581      * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
2582      * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
2583      * Other words: all <b>*stubbed*</b> methods of given mocks are marked <b>*verified*</b> so that they don't get in a way during verifyNoMoreInteractions().
2584      * <p>
2585      * This method <b>changes the input mocks</b>! This method returns input mocks just for convenience.
2586      * <p>
2587      * Ignored stubs will also be ignored for verification inOrder, including {@link org.mockito.InOrder#verifyNoMoreInteractions()}.
2588      * See the second example.
2589      * <p>
2590      * Example:
2591      * <pre class="code"><code class="java">
2592      *  //mocking lists for the sake of the example (if you mock List in real you will burn in hell)
2593      *  List mock1 = mock(List.class), mock2 = mock(List.class);
2594      *
2595      *  //stubbing mocks:
2596      *  when(mock1.get(0)).thenReturn(10);
2597      *  when(mock2.get(0)).thenReturn(20);
2598      *
2599      *  //using mocks by calling stubbed get(0) methods:
2600      *  System.out.println(mock1.get(0)); //prints 10
2601      *  System.out.println(mock2.get(0)); //prints 20
2602      *
2603      *  //using mocks by calling clear() methods:
2604      *  mock1.clear();
2605      *  mock2.clear();
2606      *
2607      *  //verification:
2608      *  verify(mock1).clear();
2609      *  verify(mock2).clear();
2610      *
2611      *  //verifyNoMoreInteractions() fails because get() methods were not accounted for.
2612      *  try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
2613      *
2614      *  //However, if we ignore stubbed methods then we can verifyNoMoreInteractions()
2615      *  verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
2616      *
2617      *  //Remember that ignoreStubs() <b>*changes*</b> the input mocks and returns them for convenience.
2618      * </code></pre>
2619      * Ignoring stubs can be used with <b>verification in order</b>:
2620      * <pre class="code"><code class="java">
2621      *  List list = mock(List.class);
2622      *  when(list.get(0)).thenReturn("foo");
2623      *
2624      *  list.add(0);
2625      *  list.clear();
2626      *  System.out.println(list.get(0)); //we don't want to verify this
2627      *
2628      *  InOrder inOrder = inOrder(ignoreStubs(list));
2629      *  inOrder.verify(list).add(0);
2630      *  inOrder.verify(list).clear();
2631      *  inOrder.verifyNoMoreInteractions();
2632      * </code></pre>
2633      * Stubbed invocations are automatically verified with {@link Strictness#STRICT_STUBS} feature
2634      * and it eliminates the need for <code>ignoreStubs()</code>. Example below uses JUnit Rules:
2635      * <pre class="code"><code class="java">
2636      *  &#064;Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
2637      *
2638      *  List list = mock(List.class);
2639      *  when(list.get(0)).thenReturn("foo");
2640      *
2641      *  list.size();
2642      *  verify(list).size();
2643      *
2644      *  list.get(0); // Automatically verified by STRICT_STUBS
2645      *  verifyNoMoreInteractions(list); // No need of ignoreStubs()
2646      * </code></pre>
2647      *
2648      * @since 1.9.0
2649      * @param mocks input mocks that will be changed
2650      * @return the same mocks that were passed in as parameters
2651      */
ignoreStubs(Object... mocks)2652     public static Object[] ignoreStubs(Object... mocks) {
2653         return MOCKITO_CORE.ignoreStubs(mocks);
2654     }
2655 
2656     /**
2657      * Allows verifying exact number of invocations. E.g:
2658      * <pre class="code"><code class="java">
2659      *   verify(mock, times(2)).someMethod("some arg");
2660      * </code></pre>
2661      *
2662      * See examples in javadoc for {@link Mockito} class
2663      *
2664      * @param wantedNumberOfInvocations wanted number of invocations
2665      *
2666      * @return verification mode
2667      */
2668     @CheckReturnValue
times(int wantedNumberOfInvocations)2669     public static VerificationMode times(int wantedNumberOfInvocations) {
2670         return VerificationModeFactory.times(wantedNumberOfInvocations);
2671     }
2672 
2673     /**
2674      * Alias to <code>times(0)</code>, see {@link Mockito#times(int)}
2675      * <p>
2676      * Verifies that interaction did not happen. E.g:
2677      * <pre class="code"><code class="java">
2678      *   verify(mock, never()).someMethod();
2679      * </code></pre>
2680      *
2681      * <p>
2682      * If you want to verify there were NO interactions with the mock
2683      * check out {@link Mockito#verifyZeroInteractions(Object...)}
2684      * or {@link Mockito#verifyNoMoreInteractions(Object...)}
2685      * <p>
2686      * See examples in javadoc for {@link Mockito} class
2687      *
2688      * @return verification mode
2689      */
2690     @CheckReturnValue
never()2691     public static VerificationMode never() {
2692         return times(0);
2693     }
2694 
2695     /**
2696      * Allows at-least-once verification. E.g:
2697      * <pre class="code"><code class="java">
2698      *   verify(mock, atLeastOnce()).someMethod("some arg");
2699      * </code></pre>
2700      * Alias to <code>atLeast(1)</code>.
2701      * <p>
2702      * See examples in javadoc for {@link Mockito} class
2703      *
2704      * @return verification mode
2705      */
2706     @CheckReturnValue
atLeastOnce()2707     public static VerificationMode atLeastOnce() {
2708         return VerificationModeFactory.atLeastOnce();
2709     }
2710 
2711     /**
2712      * Allows at-least-x verification. E.g:
2713      * <pre class="code"><code class="java">
2714      *   verify(mock, atLeast(3)).someMethod("some arg");
2715      * </code></pre>
2716      *
2717      * See examples in javadoc for {@link Mockito} class
2718      *
2719      * @param minNumberOfInvocations minimum number of invocations
2720      *
2721      * @return verification mode
2722      */
2723     @CheckReturnValue
atLeast(int minNumberOfInvocations)2724     public static VerificationMode atLeast(int minNumberOfInvocations) {
2725         return VerificationModeFactory.atLeast(minNumberOfInvocations);
2726     }
2727 
2728     /**
2729      * Allows at-most-x verification. E.g:
2730      * <pre class="code"><code class="java">
2731      *   verify(mock, atMost(3)).someMethod("some arg");
2732      * </code></pre>
2733      *
2734      * See examples in javadoc for {@link Mockito} class
2735      *
2736      * @param maxNumberOfInvocations max number of invocations
2737      *
2738      * @return verification mode
2739      */
2740     @CheckReturnValue
atMost(int maxNumberOfInvocations)2741     public static VerificationMode atMost(int maxNumberOfInvocations) {
2742         return VerificationModeFactory.atMost(maxNumberOfInvocations);
2743     }
2744 
2745     /**
2746      * Allows non-greedy verification in order.  For example
2747      * <pre class="code"><code class="java">
2748      *   inOrder.verify( mock, calls( 2 )).someMethod( "some arg" );
2749      * </code></pre>
2750      * <ul>
2751      * <li>will not fail if the method is called 3 times, unlike times( 2 )</li>
2752      * <li>will not mark the third invocation as verified, unlike atLeast( 2 )</li>
2753      * </ul>
2754      * This verification mode can only be used with in order verification.
2755      * @param wantedNumberOfInvocations number of invocations to verify
2756      * @return  verification mode
2757      */
2758     @CheckReturnValue
calls( int wantedNumberOfInvocations )2759     public static VerificationMode calls( int wantedNumberOfInvocations ){
2760         return VerificationModeFactory.calls( wantedNumberOfInvocations );
2761     }
2762 
2763     /**
2764      * Allows checking if given method was the only one invoked. E.g:
2765      * <pre class="code"><code class="java">
2766      *   verify(mock, only()).someMethod();
2767      *   //above is a shorthand for following 2 lines of code:
2768      *   verify(mock).someMethod();
2769      *   verifyNoMoreInvocations(mock);
2770      * </code></pre>
2771      *
2772      * <p>
2773      * See also {@link Mockito#verifyNoMoreInteractions(Object...)}
2774      * <p>
2775      * See examples in javadoc for {@link Mockito} class
2776      *
2777      * @return verification mode
2778      */
2779     @CheckReturnValue
only()2780     public static VerificationMode only() {
2781         return VerificationModeFactory.only();
2782     }
2783 
2784     /**
2785      * Verification will be triggered after given amount of millis, allowing testing of async code.
2786      * Useful when interactions with the mock object did not happened yet.
2787      * Extensive use of after() method can be a code smell - there are better ways of testing concurrent code.
2788      * <p>
2789      * See also {@link #after(long)} method for testing async code.
2790      * Differences between {@code timeout()} and {@code after} are explained in Javadoc for {@link #after(long)}.
2791      * <p>
2792      * Extensive use of {@code timeout()} method can be a code smell - there are better ways of testing concurrent code.
2793      * <pre class="code"><code class="java">
2794      *   //passes when someMethod() is called no later than within 100 ms
2795      *   //exits immediately when verification is satisfied (e.g. may not wait full 100 ms)
2796      *   verify(mock, timeout(100)).someMethod();
2797      *   //above is an alias to:
2798      *   verify(mock, timeout(100).times(1)).someMethod();
2799      *
2800      *   //passes as soon as someMethod() has been called 2 times under 100 ms
2801      *   verify(mock, timeout(100).times(2)).someMethod();
2802      *
2803      *   //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms
2804      *   verify(mock, timeout(100).atLeast(2)).someMethod();
2805      * </code></pre>
2806      *
2807      * See examples in javadoc for {@link Mockito} class
2808      *
2809      * @param millis - duration in milliseconds
2810      *
2811      * @return object that allows fluent specification of the verification (times(x), atLeast(y), etc.)
2812      */
2813     @CheckReturnValue
timeout(long millis)2814     public static VerificationWithTimeout timeout(long millis) {
2815         return new Timeout(millis, VerificationModeFactory.times(1));
2816     }
2817 
2818     /**
2819      * Verification will be triggered after given amount of millis, allowing testing of async code.
2820      * Useful when interactions with the mock object did not happened yet.
2821      * Extensive use of after() method can be a code smell - there are better ways of testing concurrent code.
2822      * <p>
2823      * Not yet implemented to work with InOrder verification.
2824      * <p>
2825      * See also {@link #timeout(long)} method for testing async code.
2826      * Differences between {@code timeout()} and {@code after()} are explained below.
2827      *
2828      * <pre class="code"><code class="java">
2829      *   //passes after 100ms, if someMethod() has only been called once at that time.
2830      *   verify(mock, after(100)).someMethod();
2831      *   //above is an alias to:
2832      *   verify(mock, after(100).times(1)).someMethod();
2833      *
2834      *   //passes if someMethod() is called <b>*exactly*</b> 2 times, as tested after 100 millis
2835      *   verify(mock, after(100).times(2)).someMethod();
2836      *
2837      *   //passes if someMethod() has not been called, as tested after 100 millis
2838      *   verify(mock, after(100).never()).someMethod();
2839      *
2840      *   //verifies someMethod() after a given time span using given verification mode
2841      *   //useful only if you have your own custom verification modes.
2842      *   verify(mock, new After(100, yourOwnVerificationMode)).someMethod();
2843      * </code></pre>
2844      *
2845      * <strong>timeout() vs. after()</strong>
2846      * <ul>
2847      *     <li>timeout() exits immediately with success when verification passes</li>
2848      *     <li>after() awaits full duration to check if verification passes</li>
2849      * </ul>
2850      * Examples:
2851      * <pre class="code"><code class="java">
2852      *   //1.
2853      *   mock.foo();
2854      *   verify(mock, after(1000)).foo();
2855      *   //waits 1000 millis and succeeds
2856      *
2857      *   //2.
2858      *   mock.foo();
2859      *   verify(mock, timeout(1000)).foo();
2860      *   //succeeds immediately
2861      * </code></pre>
2862      *
2863      * See examples in javadoc for {@link Mockito} class
2864      *
2865      * @param millis - duration in milliseconds
2866      *
2867      * @return object that allows fluent specification of the verification
2868      */
2869     @CheckReturnValue
after(long millis)2870     public static VerificationAfterDelay after(long millis) {
2871         return new After(millis, VerificationModeFactory.times(1));
2872     }
2873 
2874     /**
2875      * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
2876      * <p>
2877      * In case of questions you may also post to mockito mailing list: <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
2878      * <p>
2879      * <code>validateMockitoUsage()</code> <b>explicitly validates</b> the framework state to detect invalid use of Mockito.
2880      * However, this feature is optional <b>because Mockito validates the usage all the time...</b> but there is a gotcha so read on.
2881      * <p>
2882      * Examples of incorrect use:
2883      * <pre class="code"><code class="java">
2884      * //Oops, thenReturn() part is missing:
2885      * when(mock.get());
2886      *
2887      * //Oops, verified method call is inside verify() where it should be on the outside:
2888      * verify(mock.execute());
2889      *
2890      * //Oops, missing method to verify:
2891      * verify(mock);
2892      * </code></pre>
2893      *
2894      * Mockito throws exceptions if you misuse it so that you know if your tests are written correctly.
2895      * The gotcha is that Mockito does the validation <b>next time</b> you use the framework (e.g. next time you verify, stub, call mock etc.).
2896      * But even though the exception might be thrown in the next test,
2897      * the exception <b>message contains a navigable stack trace element</b> with location of the defect.
2898      * Hence you can click and find the place where Mockito was misused.
2899      * <p>
2900      * Sometimes though, you might want to validate the framework usage explicitly.
2901      * For example, one of the users wanted to put <code>validateMockitoUsage()</code> in his <code>&#064;After</code> method
2902      * so that he knows immediately when he misused Mockito.
2903      * Without it, he would have known about it not sooner than <b>next time</b> he used the framework.
2904      * One more benefit of having <code>validateMockitoUsage()</code> in <code>&#064;After</code> is that jUnit runner and rule will always fail in the test method with defect
2905      * whereas ordinary 'next-time' validation might fail the <b>next</b> test method.
2906      * But even though JUnit might report next test as red, don't worry about it
2907      * and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito.
2908      * <p>
2909      * <b>Both built-in runner: {@link MockitoJUnitRunner} and rule: {@link MockitoRule}</b> do validateMockitoUsage() after each test method.
2910      * <p>
2911      * Bear in mind that <b>usually you don't have to <code>validateMockitoUsage()</code></b>
2912      * and framework validation triggered on next-time basis should be just enough,
2913      * mainly because of enhanced exception message with clickable location of defect.
2914      * However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure
2915      * (like your own runner or base class for all tests) because adding a special action to <code>&#064;After</code> has zero cost.
2916      * <p>
2917      * See examples in javadoc for {@link Mockito} class
2918      */
validateMockitoUsage()2919     public static void validateMockitoUsage() {
2920         MOCKITO_CORE.validateMockitoUsage();
2921     }
2922 
2923     /**
2924      * Allows mock creation with additional mock settings.
2925      * <p>
2926      * Don't use it too often.
2927      * Consider writing simple tests that use simple mocks.
2928      * Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
2929      * If you cannot write a test in a simple way - refactor the code under test.
2930      * <p>
2931      * Examples of mock settings:
2932      * <pre class="code"><code class="java">
2933      *   //Creates mock with different default answer & name
2934      *   Foo mock = mock(Foo.class, withSettings()
2935      *       .defaultAnswer(RETURNS_SMART_NULLS)
2936      *       .name("cool mockie"));
2937      *
2938      *   //Creates mock with different default answer, descriptive name and extra interfaces
2939      *   Foo mock = mock(Foo.class, withSettings()
2940      *       .defaultAnswer(RETURNS_SMART_NULLS)
2941      *       .name("cool mockie")
2942      *       .extraInterfaces(Bar.class));
2943      * </code></pre>
2944      * {@link MockSettings} has been introduced for two reasons.
2945      * Firstly, to make it easy to add another mock settings when the demand comes.
2946      * Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.
2947      * <p>
2948      * See javadoc for {@link MockSettings} to learn about possible mock settings.
2949      * <p>
2950      *
2951      * @return mock settings instance with defaults.
2952      */
2953     @CheckReturnValue
withSettings()2954     public static MockSettings withSettings() {
2955         return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS);
2956     }
2957 
2958     /**
2959      * Adds a description to be printed if verification fails.
2960      * <pre class="code"><code class="java">
2961      * verify(mock, description("This will print on failure")).someMethod("some arg");
2962      * </code></pre>
2963      * @param description The description to print on failure.
2964      * @return verification mode
2965      * @since 2.1.0
2966      */
2967     @CheckReturnValue
description(String description)2968     public static VerificationMode description(String description) {
2969         return times(1).description(description);
2970     }
2971 
2972     /**
2973      * @deprecated - please use {@link MockingDetails#printInvocations()} instead.
2974      * An instance of {@code MockingDetails} can be retrieved via {@link #mockingDetails(Object)}.
2975      */
2976     @Deprecated
2977     @CheckReturnValue
debug()2978     static MockitoDebugger debug() {
2979         return new MockitoDebuggerImpl();
2980     }
2981 
2982     /**
2983      * For advanced users or framework integrators. See {@link MockitoFramework} class.
2984      *
2985      * @since 2.1.0
2986      */
2987     @Incubating
2988     @CheckReturnValue
framework()2989     public static MockitoFramework framework() {
2990         return new DefaultMockitoFramework();
2991     }
2992 
2993     /**
2994      * {@code MockitoSession} is an optional, highly recommended feature
2995      * that helps driving cleaner tests by eliminating boilerplate code and adding extra validation.
2996      * <p>
2997      * For more information, including use cases and sample code, see the javadoc for {@link MockitoSession}.
2998      *
2999      * @since 2.7.0
3000      */
3001     @Incubating
3002     @CheckReturnValue
mockitoSession()3003     public static MockitoSessionBuilder mockitoSession() {
3004         return new DefaultMockitoSessionBuilder();
3005     }
3006 
3007     /**
3008      * Lenient stubs bypass "strict stubbing" validation (see {@link Strictness#STRICT_STUBS}).
3009      * When stubbing is declared as lenient, it will not be checked for potential stubbing problems such as
3010      * 'unnecessary stubbing' ({@link UnnecessaryStubbingException}) or for 'stubbing argument mismatch' {@link PotentialStubbingProblem}.
3011      *
3012      * <pre class="code"><code class="java">
3013      *   lenient().when(mock.foo()).thenReturn("ok");
3014      * </code></pre>
3015      *
3016      * Most mocks in most tests don't need leniency and should happily prosper with {@link Strictness#STRICT_STUBS}.
3017      * <ul>
3018      *     <li>If a specific stubbing needs to be lenient - use this method</li>
3019      *     <li>If a specific mock need to have stubbings lenient - use {@link MockSettings#lenient()}</li>
3020      *     <li>If a specific test method / test class needs to have all stubbings lenient
3021      *          - configure strictness using our JUnit support ({@link MockitoJUnit} or Mockito Session ({@link MockitoSession})</li>
3022      *
3023      * <h3>Elaborate example</h3>
3024      *
3025      * In below example, 'foo.foo()' is a stubbing that was moved to 'before()' method to avoid duplication.
3026      * Doing so makes one of the test methods ('test3()') fail with 'unnecessary stubbing'.
3027      * To resolve it we can configure 'foo.foo()' stubbing in 'before()' method to be lenient.
3028      * Alternatively, we can configure entire 'foo' mock as lenient.
3029      * <p>
3030      * This example is simplified and not realistic.
3031      * Pushing stubbings to 'before()' method may cause tests to be less readable.
3032      * Some repetition in tests is OK, use your own judgement to write great tests!
3033      * It is not desired to eliminate all possible duplication from the test code
3034      * because it may add complexity and conceal important test information.
3035      *
3036      * <pre class="code"><code class="java">
3037      * public class SomeTest {
3038      *
3039      *     &#064;Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(STRICT_STUBS);
3040      *
3041      *     &#064;Mock Foo foo;
3042      *     &#064;Mock Bar bar;
3043      *
3044      *     &#064;Before public void before() {
3045      *         when(foo.foo()).thenReturn("ok");
3046      *
3047      *         // it is better to configure the stubbing to be lenient:
3048      *         // lenient().when(foo.foo()).thenReturn("ok");
3049      *
3050      *         // or the entire mock to be lenient:
3051      *         // foo = mock(Foo.class, withSettings().lenient());
3052      *     }
3053      *
3054      *     &#064;Test public void test1() {
3055      *         foo.foo();
3056      *     }
3057      *
3058      *     &#064;Test public void test2() {
3059      *         foo.foo();
3060      *     }
3061      *
3062      *     &#064;Test public void test3() {
3063      *         bar.bar();
3064      *     }
3065      * }
3066      * </code></pre>
3067      *
3068      * @since 2.20.0
3069      */
3070     @Incubating
lenient()3071     public static LenientStubber lenient() {
3072         return MOCKITO_CORE.lenient();
3073     }
3074 }
3075