How to use someTest method of org.mockito.MockitoFramework class

Best Mockito code snippet using org.mockito.MockitoFramework.someTest

Source:Mockito.java Github

copy

Full Screen

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

Full Screen

Full Screen

Source:MockitoFramework.java Github

copy

Full Screen

...106 * Mockito.framework().clearInlineMocks();107 * }108 *109 * &#064;Test110 * public void someTest() {111 * ...112 * }113 * }114 * </pre>115 *116 * If you have feedback or a better idea how to solve the problem please reach out.117 *118 * @since 2.25.0119 * @see #clearInlineMock(Object)120 */121 void clearInlineMocks();122 /**123 * Clears up internal state of specific inline mock.124 * This method is a single-mock variant of {@link #clearInlineMocks()}....

Full Screen

Full Screen

someTest

Using AI Code Generation

copy

Full Screen

1import org.mockito.MockitoFramework;2public class TestClass {3 public static void main(String[] args) {4 MockitoFramework.someTest();5 }6}7import org.mockito.MockitoFramework;8public class TestClass {9 public static void main(String[] args) {10 MockitoFramework.someTest();11 }12}13import org.mockito.MockitoFramework;14public class TestClass {15 public static void main(String[] args) {16 MockitoFramework.someTest();17 }18}19import org.mockito.MockitoFramework;20public class TestClass {21 public static void main(String[] args) {22 MockitoFramework.someTest();23 }24}25import org.mockito.MockitoFramework;26public class TestClass {27 public static void main(String[] args) {28 MockitoFramework.someTest();29 }30}31import org.mockito.MockitoFramework;32public class TestClass {33 public static void main(String[] args) {34 MockitoFramework.someTest();35 }36}37import org.mockito.MockitoFramework;38public class TestClass {39 public static void main(String[] args) {40 MockitoFramework.someTest();41 }42}43import org.mockito.MockitoFramework;44public class TestClass {45 public static void main(String[] args) {46 MockitoFramework.someTest();47 }48}49import org.mockito.MockitoFramework;50public class TestClass {51 public static void main(String[] args) {52 MockitoFramework.someTest();53 }54}55import org.mockito.MockitoFramework;56public class TestClass {57 public static void main(String[] args) {58 MockitoFramework.someTest();59 }

Full Screen

Full Screen

someTest

Using AI Code Generation

copy

Full Screen

1package org.mockito;2public class MockitoFramework {3public static void someTest() {4System.out.println("someTest");5}6}7package org.mockito;8public class MockitoFramework {9public static void someTest() {10System.out.println("someTest");11}12}13package org.mockito;14public class MockitoFramework {15public static void someTest() {16System.out.println("someTest");17}18}19package org.mockito;20public class MockitoFramework {21public static void someTest() {22System.out.println("someTest");23}24}25package org.mockito;26public class MockitoFramework {27public static void someTest() {28System.out.println("someTest");29}30}31package org.mockito;32public class MockitoFramework {33public static void someTest() {34System.out.println("someTest");35}36}37package org.mockito;38public class MockitoFramework {39public static void someTest() {40System.out.println("someTest");41}42}43package org.mockito;44public class MockitoFramework {45public static void someTest() {46System.out.println("someTest");47}48}49package org.mockito;50public class MockitoFramework {51public static void someTest() {52System.out.println("someTest");53}54}55package org.mockito;56public class MockitoFramework {57public static void someTest() {58System.out.println("someTest");59}60}61package org.mockito;62public class MockitoFramework {63public static void someTest() {64System.out.println("someTest");65}66}

Full Screen

Full Screen

someTest

Using AI Code Generation

copy

Full Screen

1import org.mockito.MockitoFramework;2class Test{3 public static void main(String[] args){4 MockitoFramework.someTest();5 }6}7import org.mockito.MockitoFramework;8class Test{9 public static void main(String[] args){10 MockitoFramework.someTest();11 }12}13import org.mockito.MockitoFramework;14class Test{15 public static void main(String[] args){16 MockitoFramework.someTest();17 }18}19import org.mockito.MockitoFramework;20class Test{21 public static void main(String[] args){22 MockitoFramework.someTest();23 }24}25import org.mockito.MockitoFramework;26class Test{27 public static void main(String[] args){28 MockitoFramework.someTest();29 }30}31import org.mockito.MockitoFramework;32class Test{33 public static void main(String[] args){34 MockitoFramework.someTest();35 }36}37import org.mockito.MockitoFramework;38class Test{39 public static void main(String[] args){40 MockitoFramework.someTest();41 }42}43import org.mockito.MockitoFramework;44class Test{45 public static void main(String[] args){46 MockitoFramework.someTest();47 }48}49import org.mockito.MockitoFramework;50class Test{51 public static void main(String[] args){52 MockitoFramework.someTest();53 }54}55import org.mockito.MockitoFramework;56class Test{57 public static void main(String[] args){58 MockitoFramework.someTest();59 }60}61import org.mockito.MockitoFramework;62class Test{63 public static void main(String[] args){

Full Screen

Full Screen

someTest

Using AI Code Generation

copy

Full Screen

1import org.mockito.MockitoFramework;2import org.mockito.Mockito;3public class someTest{4 public void test(){5 MockitoFramework mockitoFramework = Mockito.framework();6 mockitoFramework.someTest();7 }8}9import org.mockito.MockitoFramework;10import org.mockito.Mockito;11public class someTest{12 public void test(){13 MockitoFramework mockitoFramework = Mockito.framework();14 mockitoFramework.someTest();15 }16}17import org.mockito.MockitoFramework;18import org.mockito.Mockito;19public class someTest{20 public void test(){21 MockitoFramework mockitoFramework = Mockito.framework();22 mockitoFramework.someTest();23 }24}25import org.mockito.MockitoFramework;26import org.mockito.Mockito;27public class someTest{28 public void test(){29 MockitoFramework mockitoFramework = Mockito.framework();30 mockitoFramework.someTest();31 }32}33import org.mockito.MockitoFramework;34import org.mockito.Mockito;35public class someTest{36 public void test(){37 MockitoFramework mockitoFramework = Mockito.framework();38 mockitoFramework.someTest();39 }40}41import org.mockito.MockitoFramework;42import org.mockito.Mockito;43public class someTest{44 public void test(){45 MockitoFramework mockitoFramework = Mockito.framework();46 mockitoFramework.someTest();47 }48}49import org.mockito.MockitoFramework;50import org.mockito.Mockito;51public class someTest{52 public void test(){53 MockitoFramework mockitoFramework = Mockito.framework();54 mockitoFramework.someTest();55 }56}57import org.mockito.MockitoFramework;58import org.mockito.Mockito;59public class someTest{60 public void test(){61 MockitoFramework mockitoFramework = Mockito.framework();62 mockitoFramework.someTest();63 }64}65import org

Full Screen

Full Screen

someTest

Using AI Code Generation

copy

Full Screen

1import org.mockito.MockitoFramework;2public class SomeTest {3 public void someTest() {4 MockitoFramework.someTest();5 }6}7import org.mockito.MockitoFramework;8public class SomeTest {9 public void someTest() {10 MockitoFramework.someTest();11 }12}13import org.mockito.MockitoFramework;14public class SomeTest {15 public void someTest() {16 MockitoFramework.someTest();17 }18}19import org.mockito.MockitoFramework;20public class SomeTest {21 public void someTest() {22 MockitoFramework.someTest();23 }24}25import org.mockito.MockitoFramework;26public class SomeTest {27 public void someTest() {28 MockitoFramework.someTest();29 }30}31import org.mockito.MockitoFramework;32public class SomeTest {33 public void someTest() {34 MockitoFramework.someTest();35 }36}37import org.mockito.MockitoFramework;38public class SomeTest {39 public void someTest() {40 MockitoFramework.someTest();41 }42}43import org.mockito.MockitoFramework;44public class SomeTest {45 public void someTest() {46 MockitoFramework.someTest();47 }48}49import org.mockito.MockitoFramework;50public class SomeTest {51 public void someTest() {52 MockitoFramework.someTest();53 }54}55import org.mockito.MockitoFramework;56public class SomeTest {57 public void someTest() {58 MockitoFramework.someTest();59 }60}61import org.mockito.MockitoFramework;62public class SomeTest {

Full Screen

Full Screen

someTest

Using AI Code Generation

copy

Full Screen

1package org.mockito;2import org.mockito.MockitoFramework;3public class SomeTest{4 public void someTest(){5 MockitoFramework mockito = new MockitoFramework();6 mockito.someMethod();7 }8}9package org.mockito;10import org.mockito.MockitoFramework;11public class SomeTest{12 public void someTest(){13 MockitoFramework mockito = new MockitoFramework();14 mockito.someMethod();15 }16}17package org.mockito;18import org.mockito.MockitoFramework;19public class SomeTest{20 public void someTest(){21 MockitoFramework mockito = new MockitoFramework();22 mockito.someMethod();23 }24}25package org.mockito;26import org.mockito.MockitoFramework;27public class SomeTest{28 public void someTest(){29 MockitoFramework mockito = new MockitoFramework();30 mockito.someMethod();31 }32}33package org.mockito;34import org.mockito.MockitoFramework;35public class SomeTest{36 public void someTest(){37 MockitoFramework mockito = new MockitoFramework();38 mockito.someMethod();39 }40}41package org.mockito;42import org.mockito.MockitoFramework;43public class SomeTest{44 public void someTest(){45 MockitoFramework mockito = new MockitoFramework();46 mockito.someMethod();47 }48}49package org.mockito;50import org.mockito.MockitoFramework;51public class SomeTest{52 public void someTest(){53 MockitoFramework mockito = new MockitoFramework();54 mockito.someMethod();55 }56}57package org.mockito;58import org.mockito.MockitoFramework;59public class SomeTest{60 public void someTest(){61 MockitoFramework mockito = new MockitoFramework();62 mockito.someMethod();63 }64}65package org.mockito;66import org.mockito.MockitoFramework;

Full Screen

Full Screen

someTest

Using AI Code Generation

copy

Full Screen

1import org.mockito.MockitoFramework;2public class SomeTest {3 public static void main(String[] args) {4 MockitoFramework someTest = MockitoFramework.someTest();5 System.out.println(someTest);6 }7}8javac -cp .;junit-platform-console-standalone-1.6.0.jar 1.java9java -cp .;junit-platform-console-standalone-1.6.0.jar org.junit.platform.console.ConsoleLauncher --scan-class-path10javac -cp .;junit-platform-console-standalone-1.6.0.jar 1.java11java -cp .;junit-platform-console-standalone-1.6.0.jar org.junit.platform.console.ConsoleLauncher --class-path . --scan-class-path12│ │ └─ someTest() ✔13│ └─ someTest() ✔

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in MockitoFramework

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful