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