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