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