1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5package org.mockito; 6 7import org.mockito.internal.MockitoCore; 8import org.mockito.internal.creation.MockSettingsImpl; 9import org.mockito.internal.debugging.MockitoDebuggerImpl; 10import org.mockito.internal.stubbing.answers.*; 11import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues; 12import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues; 13import org.mockito.internal.verification.VerificationModeFactory; 14import org.mockito.runners.MockitoJUnitRunner; 15import org.mockito.stubbing.*; 16import org.mockito.verification.Timeout; 17import org.mockito.verification.VerificationMode; 18import org.mockito.verification.VerificationWithTimeout; 19 20/** 21 * <p align="left"><img src="logo.jpg"/></p> 22 * Mockito library enables mocks creation, verification and stubbing. 23 * <p> 24 * This javadoc content is also available on the <a href="http://mockito.org">http://mockito.org</a> web page. 25 * All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code. 26 * Also, it makes possible to access documentation straight from the IDE even if you work offline. 27 * 28 * <h1>Contents</h1> 29 * 30 * <b> 31 * <a href="#1">1. Let's verify some behaviour! </a><br/> 32 * <a href="#2">2. How about some stubbing? </a><br/> 33 * <a href="#3">3. Argument matchers </a><br/> 34 * <a href="#4">4. Verifying exact number of invocations / at least once / never </a><br/> 35 * <a href="#5">5. Stubbing void methods with exceptions </a><br/> 36 * <a href="#6">6. Verification in order </a><br/> 37 * <a href="#7">7. Making sure interaction(s) never happened on mock </a><br/> 38 * <a href="#8">8. Finding redundant invocations </a><br/> 39 * <a href="#9">9. Shorthand for mocks creation - <code>@Mock</code> annotation </a><br/> 40 * <a href="#10">10. Stubbing consecutive calls (iterator-style stubbing) </a><br/> 41 * <a href="#11">11. Stubbing with callbacks </a><br/> 42 * <a href="#12">12. <code>doReturn()</code>|<code>doThrow()</code>|<code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a><br/> 43 * <a href="#13">13. Spying on real objects </a><br/> 44 * <a href="#14">14. Changing default return values of unstubbed invocations (Since 1.7) </a><br/> 45 * <a href="#15">15. Capturing arguments for further assertions (Since 1.8.0) </a><br/> 46 * <a href="#16">16. Real partial mocks (Since 1.8.0) </a><br/> 47 * <a href="#17">17. Resetting mocks (Since 1.8.0) </a><br/> 48 * <a href="#18">18. Troubleshooting & validating framework usage (Since 1.8.0) </a><br/> 49 * <a href="#19">19. Aliases for behavior driven development (Since 1.8.0) </a><br/> 50 * <a href="#20">20. Serializable mocks (Since 1.8.1) </a><br/> 51 * <a href="#21">21. New annotations: <code>@Captor</code>, <code>@Spy</code>, <code>@InjectMocks</code> (Since 1.8.3) </a><br/> 52 * <a href="#22">22. Verification with timeout (Since 1.8.5) </a><br/> 53 * <a href="#23">23. (New) Automatic instantiation of <code>@Spies</code>, <code>@InjectMocks</code> and constructor injection goodness (Since 1.9.0)</a><br/> 54 * <a href="#24">24. (New) One-liner stubs (Since 1.9.0)</a><br/> 55 * <a href="#25">25. (New) Verification ignoring stubs (Since 1.9.0)</a><br/> 56 * <a href="#26">26. (**New**) Mocking details (Since 1.9.5)</a><br/> 57 * <a href="#27">27. (**New**) Delegate calls to real instance (Since 1.9.5)</a><br/> 58 * <a href="#28">28. (**New**) <code>MockMaker</code> API (Since 1.9.5)</a><br/> 59 * </b> 60 * 61 * <p> 62 * Following examples mock a List, because everyone knows its interface (methods 63 * like <code>add()</code>, <code>get()</code>, <code>clear()</code> will be used). <br> 64 * You probably wouldn't mock List class 'in real'. 65 * 66 * 67 * 68 * 69 * <h3 id="1">1. <a class="meaningful_link" href="#verification">Let's verify some behaviour!</a></h3> 70 * 71 * <pre class="code"><code class="java"> 72 * //Let's import Mockito statically so that the code looks clearer 73 * import static org.mockito.Mockito.*; 74 * 75 * //mock creation 76 * List mockedList = mock(List.class); 77 * 78 * //using mock object 79 * mockedList.add("one"); 80 * mockedList.clear(); 81 * 82 * //verification 83 * verify(mockedList).add("one"); 84 * verify(mockedList).clear(); 85 * </code></pre> 86 * 87 * <p> 88 * Once created, mock will remember all interactions. Then you can selectively 89 * verify whatever interaction you are interested in. 90 * 91 * 92 * 93 * 94 * <h3 id="2">2. <a class="meaningful_link" href="#stubbing">How about some stubbing?</a></h3> 95 * 96 * <pre class="code"><code class="java"> 97 * //You can mock concrete classes, not only interfaces 98 * LinkedList mockedList = mock(LinkedList.class); 99 * 100 * //stubbing 101 * when(mockedList.get(0)).thenReturn("first"); 102 * when(mockedList.get(1)).thenThrow(new RuntimeException()); 103 * 104 * //following prints "first" 105 * System.out.println(mockedList.get(0)); 106 * 107 * //following throws runtime exception 108 * System.out.println(mockedList.get(1)); 109 * 110 * //following prints "null" because get(999) was not stubbed 111 * System.out.println(mockedList.get(999)); 112 * 113 * //Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b> 114 * //If your code cares what get(0) returns then something else breaks (often before even verify() gets executed). 115 * //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>. 116 * verify(mockedList).get(0); 117 * </code></pre> 118 * 119 * <ul> 120 * <li> By default, for all methods that return value, mock returns null, an 121 * empty collection or appropriate primitive/primitive wrapper value (e.g: 0, 122 * false, ... for int/Integer, boolean/Boolean, ...). </li> 123 * 124 * <li> Stubbing can be overridden: for example common stubbing can go to 125 * fixture setup but the test methods can override it. 126 * Please note that overridding stubbing is a potential code smell that points out too much stubbing</li> 127 * 128 * <li> Once stubbed, the method will always return stubbed value regardless 129 * of how many times it is called. </li> 130 * 131 * <li> Last stubbing is more important - when you stubbed the same method with 132 * the same arguments many times. 133 * Other words: <b>the order of stubbing matters</b> but it is only meaningful rarely, 134 * e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.</li> 135 * 136 * </ul> 137 * 138 * 139 * 140 * <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers">Argument matchers</a></h3> 141 * 142 * Mockito verifies argument values in natural java style: by using an <code>equals()</code> method. 143 * Sometimes, when extra flexibility is required then you might use argument matchers: 144 * 145 * <pre class="code"><code class="java"> 146 * //stubbing using built-in anyInt() argument matcher 147 * when(mockedList.get(anyInt())).thenReturn("element"); 148 * 149 * //stubbing using hamcrest (let's say isValid() returns your own hamcrest matcher): 150 * when(mockedList.contains(argThat(isValid()))).thenReturn("element"); 151 * 152 * //following prints "element" 153 * System.out.println(mockedList.get(999)); 154 * 155 * //<b>you can also verify using an argument matcher</b> 156 * verify(mockedList).get(anyInt()); 157 * </code></pre> 158 * 159 * <p> 160 * Argument matchers allow flexible verification or stubbing. 161 * {@link Matchers Click here to see} more built-in matchers 162 * and examples of <b>custom argument matchers / hamcrest matchers</b>. 163 * <p> 164 * For information solely on <b>custom argument matchers</b> check out javadoc for {@link ArgumentMatcher} class. 165 * <p> 166 * Be reasonable with using complicated argument matching. 167 * The natural matching style using <code>equals()</code> with occasional <code>anyX()</code> matchers tend to give clean & simple tests. 168 * 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. 169 * <p> 170 * Also, read <a href="#15">section 15</a> or javadoc for {@link ArgumentCaptor} class. 171 * {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions. 172 * <p> 173 * <b>Warning on argument matchers:</b> 174 * <p> 175 * If you are using argument matchers, <b>all arguments</b> have to be provided 176 * by matchers. 177 * <p> 178 * E.g: (example shows verification but the same applies to stubbing): 179 * 180 * <pre class="code"><code class="java"> 181 * verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>); 182 * //above is correct - eq() is also an argument matcher 183 * 184 * verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>); 185 * //above is incorrect - exception will be thrown because third argument is given without an argument matcher. 186 * </code></pre> 187 * 188 * <p> 189 * Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers. 190 * Internally, they record a matcher on a stack and return a dummy value (usually null). 191 * This implementation is due static type safety imposed by java compiler. 192 * The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method. 193 * 194 * 195 * 196 * 197 * <h3 id="4">4. <a class="meaningful_link" href="#exact_verification">Verifying exact number of invocations</a> / 198 * <a class="meaningful_link" href="#at_least_verification">at least x</a> / never</h3> 199 * 200 * <pre class="code"><code class="java"> 201 * //using mock 202 * mockedList.add("once"); 203 * 204 * mockedList.add("twice"); 205 * mockedList.add("twice"); 206 * 207 * mockedList.add("three times"); 208 * mockedList.add("three times"); 209 * mockedList.add("three times"); 210 * 211 * //following two verifications work exactly the same - times(1) is used by default 212 * verify(mockedList).add("once"); 213 * verify(mockedList, times(1)).add("once"); 214 * 215 * //exact number of invocations verification 216 * verify(mockedList, times(2)).add("twice"); 217 * verify(mockedList, times(3)).add("three times"); 218 * 219 * //verification using never(). never() is an alias to times(0) 220 * verify(mockedList, never()).add("never happened"); 221 * 222 * //verification using atLeast()/atMost() 223 * verify(mockedList, atLeastOnce()).add("three times"); 224 * verify(mockedList, atLeast(2)).add("five times"); 225 * verify(mockedList, atMost(5)).add("three times"); 226 * 227 * </code></pre> 228 * 229 * <p> 230 * <b>times(1) is the default.</b> Therefore using times(1) explicitly can be 231 * omitted. 232 * 233 * 234 * 235 * 236 * <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3> 237 * 238 * <pre class="code"><code class="java"> 239 * doThrow(new RuntimeException()).when(mockedList).clear(); 240 * 241 * //following throws RuntimeException: 242 * mockedList.clear(); 243 * </code></pre> 244 * 245 * Read more about doThrow|doAnswer family of methods in paragraph 12. 246 * <p> 247 * Initially, {@link Mockito#stubVoid(Object)} was used for stubbing voids. 248 * Currently <code>stubVoid()</code> is deprecated in favor of {@link Mockito#doThrow(Throwable)}. 249 * This is because of improved readability and consistency with the family of {@link Mockito#doAnswer(Answer)} methods. 250 * 251 * 252 * 253 * 254 * <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification">Verification in order</a></h3> 255 * 256 * <pre class="code"><code class="java"> 257 * // A. Single mock whose methods must be invoked in a particular order 258 * List singleMock = mock(List.class); 259 * 260 * //using a single mock 261 * singleMock.add("was added first"); 262 * singleMock.add("was added second"); 263 * 264 * //create an inOrder verifier for a single mock 265 * InOrder inOrder = inOrder(singleMock); 266 * 267 * //following will make sure that add is first called with "was added first, then with "was added second" 268 * inOrder.verify(singleMock).add("was added first"); 269 * inOrder.verify(singleMock).add("was added second"); 270 * 271 * // B. Multiple mocks that must be used in a particular order 272 * List firstMock = mock(List.class); 273 * List secondMock = mock(List.class); 274 * 275 * //using mocks 276 * firstMock.add("was called first"); 277 * secondMock.add("was called second"); 278 * 279 * //create inOrder object passing any mocks that need to be verified in order 280 * InOrder inOrder = inOrder(firstMock, secondMock); 281 * 282 * //following will make sure that firstMock was called before secondMock 283 * inOrder.verify(firstMock).add("was called first"); 284 * inOrder.verify(secondMock).add("was called second"); 285 * 286 * // Oh, and A + B can be mixed together at will 287 * </code></pre> 288 * 289 * Verification in order is flexible - <b>you don't have to verify all 290 * interactions</b> one-by-one but only those that you are interested in 291 * testing in order. 292 * <p> 293 * Also, you can create InOrder object passing only mocks that are relevant for 294 * in-order verification. 295 * 296 * 297 * 298 * 299 * <h3 id="7">7. <a class="meaningful_link" href="#never_verification">Making sure interaction(s) never happened on mock</a></h3> 300 * 301 * <pre class="code"><code class="java"> 302 * //using mocks - only mockOne is interacted 303 * mockOne.add("one"); 304 * 305 * //ordinary verification 306 * verify(mockOne).add("one"); 307 * 308 * //verify that method was never called on a mock 309 * verify(mockOne, never()).add("two"); 310 * 311 * //verify that other mocks were not interacted 312 * verifyZeroInteractions(mockTwo, mockThree); 313 * 314 * </code></pre> 315 * 316 * 317 * 318 * 319 * <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations">Finding redundant invocations</a></h3> 320 * 321 * <pre class="code"><code class="java"> 322 * //using mocks 323 * mockedList.add("one"); 324 * mockedList.add("two"); 325 * 326 * verify(mockedList).add("one"); 327 * 328 * //following verification will fail 329 * verifyNoMoreInteractions(mockedList); 330 * </code></pre> 331 * 332 * A word of <b>warning</b>: 333 * 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. 334 * <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method. 335 * <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant. 336 * Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests. You can find further reading 337 * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>. 338 * 339 * <p> 340 * See also {@link Mockito#never()} - it is more explicit and 341 * communicates the intent well. 342 * <p> 343 * 344 * 345 * 346 * 347 * <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation">Shorthand for mocks creation - <code>@Mock</code> annotation</a></h3> 348 * 349 * <ul> 350 * <li>Minimizes repetitive mock creation code.</li> 351 * <li>Makes the test class more readable.</li> 352 * <li>Makes the verification error easier to read because the <b>field name</b> 353 * is used to identify the mock.</li> 354 * </ul> 355 * 356 * <pre class="code"><code class="java"> 357 * public class ArticleManagerTest { 358 * 359 * @Mock private ArticleCalculator calculator; 360 * @Mock private ArticleDatabase database; 361 * @Mock private UserProvider userProvider; 362 * 363 * private ArticleManager manager; 364 * </code></pre> 365 * 366 * <b>Important!</b> This needs to be somewhere in the base class or a test 367 * runner: 368 * 369 * <pre class="code"><code class="java"> 370 * MockitoAnnotations.initMocks(testClass); 371 * </code></pre> 372 * 373 * You can use built-in runner: {@link MockitoJUnitRunner}. 374 * <p> 375 * Read more here: {@link MockitoAnnotations} 376 * 377 * 378 * 379 * 380 * <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3> 381 * 382 * Sometimes we need to stub with different return value/exception for the same 383 * method call. Typical use case could be mocking iterators. 384 * Original version of Mockito did not have this feature to promote simple mocking. 385 * For example, instead of iterators one could use {@link Iterable} or simply 386 * collections. Those offer natural ways of stubbing (e.g. using real 387 * collections). In rare scenarios stubbing consecutive calls could be useful, 388 * though: 389 * <p> 390 * 391 * <pre class="code"><code class="java"> 392 * when(mock.someMethod("some arg")) 393 * .thenThrow(new RuntimeException()) 394 * .thenReturn("foo"); 395 * 396 * //First call: throws runtime exception: 397 * mock.someMethod("some arg"); 398 * 399 * //Second call: prints "foo" 400 * System.out.println(mock.someMethod("some arg")); 401 * 402 * //Any consecutive call: prints "foo" as well (last stubbing wins). 403 * System.out.println(mock.someMethod("some arg")); 404 * </code></pre> 405 * 406 * Alternative, shorter version of consecutive stubbing: 407 * 408 * <pre class="code"><code class="java"> 409 * when(mock.someMethod("some arg")) 410 * .thenReturn("one", "two", "three"); 411 * </code></pre> 412 * 413 * 414 * 415 * 416 * <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs">Stubbing with callbacks</a></h3> 417 * 418 * Allows stubbing with generic {@link Answer} interface. 419 * <p> 420 * Yet another controversial feature which was not included in Mockito 421 * originally. We recommend using simple stubbing with <code>thenReturn()</code> or 422 * <code>thenThrow()</code> only. Those two should be <b>just enough</b> to test/test-drive 423 * any clean & simple code. 424 * 425 * <pre class="code"><code class="java"> 426 * when(mock.someMethod(anyString())).thenAnswer(new Answer() { 427 * Object answer(InvocationOnMock invocation) { 428 * Object[] args = invocation.getArguments(); 429 * Object mock = invocation.getMock(); 430 * return "called with arguments: " + args; 431 * } 432 * }); 433 * 434 * //Following prints "called with arguments: foo" 435 * System.out.println(mock.someMethod("foo")); 436 * </code></pre> 437 * 438 * 439 * 440 * 441 * <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>| 442 * <code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a></h3> 443 * 444 * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not 445 * like void methods inside brackets... 446 * <p> 447 * {@link Mockito#doThrow(Throwable)} replaces the {@link Mockito#stubVoid(Object)} method for stubbing voids. 448 * The main reason is improved readability and consistency with the family of <code>doAnswer()</code> methods. 449 * <p> 450 * Use <code>doThrow()</code> when you want to stub a void method with an exception: 451 * <pre class="code"><code class="java"> 452 * doThrow(new RuntimeException()).when(mockedList).clear(); 453 * 454 * //following throws RuntimeException: 455 * mockedList.clear(); 456 * </code></pre> 457 * 458 * <p> 459 * You can use <code>doThrow()</code>, <code>doAnswer()</code>, <code>doNothing()</code>, <code>doReturn()</code> 460 * and <code>doCallRealMethod()</code> in place of the corresponding call with <code>when()</code>, for any method. 461 * It is necessary when you 462 * <ul> 463 * <li>stub void methods</li> 464 * <li>stub methods on spy objects (see below)</li> 465 * <li>stub the same method more than once, to change the behaviour of a mock in the middle of a test.</li> 466 * </ul> 467 * but you may prefer to use these methods in place of the alternative with <code>when()</code>, for all of your stubbing calls. 468 * <p> 469 * Read more about these methods: 470 * <p> 471 * {@link Mockito#doReturn(Object)} 472 * <p> 473 * {@link Mockito#doThrow(Throwable)} 474 * <p> 475 * {@link Mockito#doThrow(Class)} 476 * <p> 477 * {@link Mockito#doAnswer(Answer)} 478 * <p> 479 * {@link Mockito#doNothing()} 480 * <p> 481 * {@link Mockito#doCallRealMethod()} 482 * 483 * 484 * 485 * 486 * <h3 id="13">13. <a class="meaningful_link" href="#spy">Spying on real objects</a></h3> 487 * 488 * You can create spies of real objects. When you use the spy then the <b>real</b> methods are called 489 * (unless a method was stubbed). 490 * <p> 491 * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code. 492 * 493 * <p> 494 * Spying on real objects can be associated with "partial mocking" concept. 495 * <b>Before the release 1.8</b>, Mockito spies were not real partial mocks. 496 * The reason was we thought partial mock is a code smell. 497 * At some point we found legitimate use cases for partial mocks 498 * (3rd party interfaces, interim refactoring of legacy code, the full article is <a href= 499 * "http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring" 500 * >here</a>) 501 * <p> 502 * 503 * <pre class="code"><code class="java"> 504 * List list = new LinkedList(); 505 * List spy = spy(list); 506 * 507 * //optionally, you can stub out some methods: 508 * when(spy.size()).thenReturn(100); 509 * 510 * //using the spy calls <b>*real*</b> methods 511 * spy.add("one"); 512 * spy.add("two"); 513 * 514 * //prints "one" - the first element of a list 515 * System.out.println(spy.get(0)); 516 * 517 * //size() method was stubbed - 100 is printed 518 * System.out.println(spy.size()); 519 * 520 * //optionally, you can verify 521 * verify(spy).add("one"); 522 * verify(spy).add("two"); 523 * </code></pre> 524 * 525 * <h4>Important gotcha on spying real objects!</h4> 526 * <ol> 527 * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies. 528 * Therefore when using spies please consider <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code> family of 529 * methods for stubbing. Example: 530 * 531 * <pre class="code"><code class="java"> 532 * List list = new LinkedList(); 533 * List spy = spy(list); 534 * 535 * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) 536 * when(spy.get(0)).thenReturn("foo"); 537 * 538 * //You have to use doReturn() for stubbing 539 * doReturn("foo").when(spy).get(0); 540 * </code></pre> 541 * </li> 542 * 543 * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it. 544 * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction 545 * and their effect on real instance state. 546 * 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>, 547 * you won't see any effects on the real instance. 548 * </li> 549 * 550 * <li>Watch out for final methods. 551 * 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. 552 * Also you won't be able to verify those method as well. 553 * </li> 554 * </ol> 555 * 556 * 557 * 558 * 559 * <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn">default return values of unstubbed invocations</a> (Since 1.7)</h3> 560 * 561 * You can create a mock with specified strategy for its return values. 562 * It's quite advanced feature and typically you don't need it to write decent tests. 563 * However, it can be helpful for working with <b>legacy systems</b>. 564 * <p> 565 * It is the default answer so it will be used <b>only when you don't</b> stub the method call. 566 * 567 * <pre class="code"><code class="java"> 568 * Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS); 569 * Foo mockTwo = mock(Foo.class, new YourOwnAnswer()); 570 * </code></pre> 571 * 572 * <p> 573 * Read more about this interesting implementation of <i>Answer</i>: {@link Mockito#RETURNS_SMART_NULLS} 574 * 575 * 576 * 577 * 578 * <h3 id="15">15. <a class="meaningful_link" href="#captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3> 579 * 580 * Mockito verifies argument values in natural java style: by using an <code>equals()</code> method. 581 * This is also the recommended way of matching arguments because it makes tests clean & simple. 582 * In some situations though, it is helpful to assert on certain arguments after the actual verification. 583 * For example: 584 * <pre class="code"><code class="java"> 585 * ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class); 586 * verify(mock).doSomething(argument.capture()); 587 * assertEquals("John", argument.getValue().getName()); 588 * </code></pre> 589 * 590 * <b>Warning:</b> it is recommended to use ArgumentCaptor with verification <b>but not</b> with stubbing. 591 * Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block. 592 * Also it may reduce defect localization because if stubbed method was not called then no argument is captured. 593 * <p> 594 * In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class). 595 * Both techniques can be used for making sure certain arguments where passed to mocks. 596 * However, ArgumentCaptor may be a better fit if: 597 * <ul> 598 * <li>custom argument matcher is not likely to be reused</li> 599 * <li>you just need it to assert on argument values to complete verification</li> 600 * </ul> 601 * Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing. 602 * 603 * 604 * 605 * 606 * <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3> 607 * 608 * Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. 609 * Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading: 610 * <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a> 611 * <p> 612 * <b>Before release 1.8</b> <code>spy()</code> was not producing real partial mocks and it was confusing for some users. 613 * Read more about spying: <a href="#13">here</a> or in javadoc for {@link Mockito#spy(Object)} method. 614 * <p> 615 * <pre class="code"><code class="java"> 616 * //you can create partial mock with spy() method: 617 * List list = spy(new LinkedList()); 618 * 619 * //you can enable partial mock capabilities selectively on mocks: 620 * Foo mock = mock(Foo.class); 621 * //Be sure the real implementation is 'safe'. 622 * //If real implementation throws exceptions or depends on specific state of the object then you're in trouble. 623 * when(mock.someMethod()).thenCallRealMethod(); 624 * </code></pre> 625 * 626 * As usual you are going to read <b>the partial mock warning</b>: 627 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. 628 * How does partial mock fit into this paradigm? Well, it just doesn't... 629 * Partial mock usually means that the complexity has been moved to a different method on the same object. 630 * In most cases, this is not the way you want to design your application. 631 * <p> 632 * However, there are rare cases when partial mocks come handy: 633 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) 634 * However, I wouldn't use partial mocks for new, test-driven & well-designed code. 635 * 636 * 637 * 638 * 639 * <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3> 640 * 641 * Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. 642 * Normally, you don't need to reset your mocks, just create new mocks for each test method. 643 * <p> 644 * Instead of <code>reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests. 645 * <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. 646 * Follow the whisper of your test methods: "Please keep us small & focused on single behavior". 647 * There are several threads about it on mockito mailing list. 648 * <p> 649 * The only reason we added <code>reset()</code> method is to 650 * make it possible to work with container-injected mocks. 651 * See issue 55 (<a href="http://code.google.com/p/mockito/issues/detail?id=55">here</a>) 652 * or FAQ (<a href="http://code.google.com/p/mockito/wiki/FAQ">here</a>). 653 * <p> 654 * <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). 655 * <pre class="code"><code class="java"> 656 * List mock = mock(List.class); 657 * when(mock.size()).thenReturn(10); 658 * mock.add(1); 659 * 660 * reset(mock); 661 * //at this point the mock forgot any interactions & stubbing 662 * </code></pre> 663 * 664 * 665 * 666 * 667 * <h3 id="18">18. <a class="meaningful_link" href="#framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3> 668 * 669 * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: 670 * <a href="http://code.google.com/p/mockito/wiki/FAQ">http://code.google.com/p/mockito/wiki/FAQ</a> 671 * <p> 672 * In case of questions you may also post to mockito mailing list: 673 * <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a> 674 * <p> 675 * Next, you should know that Mockito validates if you use it correctly <b>all the time</b>. 676 * However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()} 677 * 678 * 679 * 680 * 681 * <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3> 682 * 683 * Behavior Driven Development style of writing tests uses <b>//given //when //then</b> comments as fundamental parts of your test methods. 684 * This is exactly how we write our tests and we warmly encourage you to do so! 685 * <p> 686 * Start learning about BDD here: <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">http://en.wikipedia.org/wiki/Behavior_Driven_Development</a> 687 * <p> 688 * 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. 689 * It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test. 690 * Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method. 691 * Now it really nicely integrates with the <b>given</b> component of a BDD style test! 692 * <p> 693 * Here is how the test might look like: 694 * <pre class="code"><code class="java"> 695 * import static org.mockito.BDDMockito.*; 696 * 697 * Seller seller = mock(Seller.class); 698 * Shop shop = new Shop(seller); 699 * 700 * public void shouldBuyBread() throws Exception { 701 * //given 702 * given(seller.askForBread()).willReturn(new Bread()); 703 * 704 * //when 705 * Goods goods = shop.buyBread(); 706 * 707 * //then 708 * assertThat(goods, containBread()); 709 * } 710 * </code></pre> 711 * 712 * 713 * 714 * 715 * <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3> 716 * 717 * Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable. 718 * <p> 719 * WARNING: This should be rarely used in unit testing. 720 * <p> 721 * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This 722 * was in a web environment and the objects from the external dependency were being serialized to pass between layers. 723 * <p> 724 * To create serializable mock use {@link MockSettings#serializable()}: 725 * <pre class="code"><code class="java"> 726 * List serializableMock = mock(List.class, withSettings().serializable()); 727 * </code></pre> 728 * <p> 729 * 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'> 730 * serialization requirements</a> are met by the class. 731 * <p> 732 * Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version 733 * which accepts MockSettings. No worries, you will hardly ever use it. 734 * 735 * <pre class="code"><code class="java"> 736 * List<Object> list = new ArrayList<Object>(); 737 * List<Object> spy = mock(ArrayList.class, withSettings() 738 * .spiedInstance(list) 739 * .defaultAnswer(CALLS_REAL_METHODS) 740 * .serializable()); 741 * </code></pre> 742 * 743 * 744 * 745 * 746 * <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation"><code>@Captor</code></a>, 747 * <a class="meaningful_link" href="#spy_annotation"><code>@Spy</code></a>, 748 * <a class="meaningful_link" href="#injectmocks_annotation"><code>@InjectMocks</code></a> (Since 1.8.3)</h3> 749 * 750 * <p> 751 * Release 1.8.3 brings new annotations that may be helpful on occasion: 752 * 753 * <ul> 754 * <li>@{@link Captor} simplifies creation of {@link ArgumentCaptor} 755 * - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings 756 * <li>@{@link Spy} - you can use it instead {@link Mockito#spy(Object)}. 757 * <li>@{@link InjectMocks} - injects mock or spy fields into tested object automatically. 758 * </ul> 759 * 760 * <p> 761 * Note that @{@link InjectMocks} can only be used in combination with the @{@link Spy} annotation, it means 762 * that Mockito will inject mocks in a partial mock under testing. As a remainder, please read point 16 about partial mocks. 763 * 764 * <p> 765 * All new annotations are <b>*only*</b> processed on {@link MockitoAnnotations#initMocks(Object)}. 766 * Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner}. 767 * <p> 768 * 769 * 770 * 771 * 772 * <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3> 773 * <p> 774 * Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired 775 * interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent 776 * conditions. 777 * <p> 778 * It feels this feature should be used rarely - figure out a better way of testing your multi-threaded system. 779 * <p> 780 * Not yet implemented to work with InOrder verification. 781 * <p> 782 * Examples: 783 * <p> 784 * <pre class="code"><code class="java"> 785 * //passes when someMethod() is called within given time span 786 * verify(mock, timeout(100)).someMethod(); 787 * //above is an alias to: 788 * verify(mock, timeout(100).times(1)).someMethod(); 789 * 790 * //passes when someMethod() is called <b>*exactly*</b> 2 times within given time span 791 * verify(mock, timeout(100).times(2)).someMethod(); 792 * 793 * //passes when someMethod() is called <b>*at least*</b> 2 times within given time span 794 * verify(mock, timeout(100).atLeast(2)).someMethod(); 795 * 796 * //verifies someMethod() within given time span using given verification mode 797 * //useful only if you have your own custom verification modes. 798 * verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod(); 799 * </code></pre> 800 * 801 * 802 * 803 * 804 * <h3 id="23">23. (New) <a class="meaningful_link" href="#automatic_instantiation">Automatic instantiation of <code>@Spies</code>, 805 * <code>@InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3> 806 * 807 * <p> 808 * Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields 809 * using <b>constructor</b> injection, <b>setter</b> injection, or <b>field</b> injection. 810 * <p> 811 * To take advantage of this feature you need to use {@link MockitoAnnotations#initMocks(Object)} or {@link MockitoJUnitRunner}. 812 * <p> 813 * Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks} 814 * <pre class="code"><code class="java"> 815 * //instead: 816 * @Spy BeerDrinker drinker = new BeerDrinker(); 817 * //you can write: 818 * @Spy BeerDrinker drinker; 819 * 820 * //same applies to @InjectMocks annotation: 821 * @InjectMocks LocalPub; 822 * </code></pre> 823 * 824 * 825 * 826 * 827 * <h3 id="24">24. (New) <a class="meaningful_link" href="#one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3> 828 * <p> 829 * Mockito will now allow you to create mocks when stubbing. 830 * Basically, it allows to create a stub in one line of code. 831 * This can be helpful to keep test code clean. 832 * For example, some boring stub can be created & stubbed at field initialization in a test: 833 * <pre class="code"><code class="java"> 834 * public class CarTest { 835 * Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock(); 836 * 837 * @Test public void should... {} 838 * </code></pre> 839 * 840 * 841 * 842 * 843 * <h3 id="25">25. (New) <a class="meaningful_link" href="#ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3> 844 * <p> 845 * Mockito will now allow to ignore stubbing for the sake of verification. 846 * Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>. 847 * Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs. 848 * <p> 849 * <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...)); 850 * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code> 851 * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)} 852 * <p>Some examples: 853 * <pre class="code"><code class="java"> 854 * verify(mock).foo(); 855 * verify(mockTwo).bar(); 856 * 857 * //ignores all stubbed methods: 858 * verifyNoMoreInvocations(ignoreStubs(mock, mockTwo)); 859 * 860 * //creates InOrder that will ignore stubbed 861 * InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo)); 862 * inOrder.verify(mock).foo(); 863 * inOrder.verify(mockTwo).bar(); 864 * inOrder.verifyNoMoreInteractions(); 865 * </code></pre> 866 * <p> 867 * Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)} 868 * 869 * 870 * 871 * 872 * <h3 id="26">26. (**New**) <a class="meaningful_link" href="#mocking_details">Mocking details</a> (Since 1.9.5)</h3> 873 * <p> 874 * To identify whether a particular object is a mock or a spy: 875 * <pre class="code"><code class="java"> 876 * Mockito.mockingDetails(someObject).isMock(); 877 * Mockito.mockingDetails(someObject).isSpy(); 878 * </code></pre> 879 * Both the {@link MockingDetails#isMock} and {@link MockingDetails#isSpy()} methods return <code>boolean</code>. 880 * As a spy is just a different kind of mock, <code>isMock()</code> returns true if the object is a spy. 881 * In future Mockito versions MockingDetails may grow and provide other useful information about the mock, 882 * e.g. invocations, stubbing info, etc. 883 * 884 * 885 * 886 * 887 * <h3 id="27">27. (**New**) <a class="meaningful_link" href="#delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3> 888 * 889 * <p>Useful for spies or partial mocks of objects <strong>that are difficult to mock or spy</strong> using the usual spy API. 890 * Possible use cases: 891 * <ul> 892 * <li>Final classes but with an interface</li> 893 * <li>Already custom proxied object</li> 894 * <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li> 895 * </ul> 896 * 897 * <p>The difference with the regular spy: 898 * <ul> 899 * <li> 900 * The regular spy ({@link #spy(Object)}) contains <strong>all</strong> state from the spied instance 901 * and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from. 902 * If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered 903 * for verifications, and they can be effectively stubbed. 904 * </li> 905 * <li> 906 * The mock that delegates simply delegates all methods to the delegate. 907 * The delegate is used all the time as methods are delegated onto it. 908 * If you call a method on a mock that delegates and it internally calls other methods on this mock, 909 * those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too. 910 * Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created. 911 * </li> 912 * </ul> 913 * 914 * <p> 915 * See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}. 916 * 917 * 918 * 919 * 920 * <h3 id="28">28. (**New**) <a class="meaningful_link" href="#mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3> 921 * <p>Driven by requirements and patches from Google Android guys Mockito now offers an extension point 922 * that allows replacing the proxy generation engine. By default, Mockito uses cglib to create dynamic proxies. 923 * <p>The extension point is for advanced users that want to extend Mockito. For example, it is now possible 924 * to use Mockito for Android testing with a help of dexmaker. 925 * <p>For more details, motivations and examples please refer to 926 * the docs for {@link org.mockito.plugins.MockMaker}. 927 * 928 */ 929@SuppressWarnings("unchecked") 930public class Mockito extends Matchers { 931 932 static final MockitoCore MOCKITO_CORE = new MockitoCore(); 933 934 /** 935 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed. 936 * Typically it just returns some empty value. 937 * <p> 938 * {@link Answer} can be used to define the return values of unstubbed invocations. 939 * <p> 940 * This implementation first tries the global configuration. 941 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.) 942 */ 943 public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS.get(); 944 945 /** 946 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}. 947 * <p> 948 * {@link Answer} can be used to define the return values of unstubbed invocations. 949 * <p> 950 * This implementation can be helpful when working with legacy code. 951 * Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException. 952 * This implementation of Answer <b>returns SmartNull instead of null</b>. 953 * <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. 954 * <p> 955 * <code>ReturnsSmartNulls</code> first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues}) 956 * then it tries to return SmartNull. If the return type is final then plain null is returned. 957 * <p> 958 * <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 2.0. 959 * <p> 960 * Example: 961 * <pre class="code"><code class="java"> 962 * Foo mock = (Foo.class, RETURNS_SMART_NULLS); 963 * 964 * //calling unstubbed method here: 965 * Stuff stuff = mock.getStuff(); 966 * 967 * //using object returned by unstubbed call: 968 * stuff.doSomething(); 969 * 970 * //Above doesn't yield NullPointerException this time! 971 * //Instead, SmartNullPointerException is thrown. 972 * //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace. 973 * </code></pre> 974 */ 975 public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS.get(); 976 977 /** 978 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)} 979 * <p> 980 * {@link Answer} can be used to define the return values of unstubbed invocations. 981 * <p> 982 * This implementation can be helpful when working with legacy code. 983 * <p> 984 * ReturnsMocks first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues}) 985 * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain null is returned. 986 * <p> 987 */ 988 public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS.get(); 989 990 /** 991 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}. 992 * <p> 993 * Example that shows how deep stub works: 994 * <pre class="code"><code class="java"> 995 * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS); 996 * 997 * // note that we're stubbing a chain of methods here: getBar().getName() 998 * when(mock.getBar().getName()).thenReturn("deep"); 999 * 1000 * // note that we're chaining method calls: getBar().getName() 1001 * assertEquals("deep", mock.getBar().getName()); 1002 * </code></pre> 1003 * </p> 1004 * 1005 * <p> 1006 * <strong>WARNING: </strong> 1007 * This feature should rarely be required for regular clean code! Leave it for legacy code. 1008 * Mocking a mock to return a mock, to return a mock, (...), to return something meaningful 1009 * hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern). 1010 * </p> 1011 * 1012 * <p> 1013 * Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>. 1014 * </p> 1015 * 1016 * <p> 1017 * Please note that this answer will return existing mocks that matches the stub. This 1018 * behavior is ok with deep stubs and allows verification to work on the last mock of the chain. 1019 * <pre class="code"><code class="java"> 1020 * when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep"); 1021 * 1022 * mock.getBar("candy bar").getThingy().getName(); 1023 * 1024 * assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName()); 1025 * verify(mock.getBar("candy bar").getThingy()).getName(); 1026 * verify(mock.getBar(anyString()).getThingy()).getName(); 1027 * </code></pre> 1028 * </p> 1029 * 1030 * <p> 1031 * Verification only works with the last mock in the chain. You can use verification modes. 1032 * <pre class="code"><code class="java"> 1033 * when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep"); 1034 * when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep"); 1035 * when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep"); 1036 * 1037 * person.getAddress("the docks").getStreet().getName(); 1038 * person.getAddress("the docks").getStreet().getLongName(); 1039 * person.getAddress("the docks").getStreet(Locale.ITALIAN).getName(); 1040 * person.getAddress("the docks").getStreet(Locale.CHINESE).getName(); 1041 * 1042 * // note that we are actually referring to the very last mock in the stubbing chain. 1043 * InOrder inOrder = inOrder( 1044 * person.getAddress("the docks").getStreet(), 1045 * person.getAddress("the docks").getStreet(Locale.CHINESE), 1046 * person.getAddress("the docks").getStreet(Locale.ITALIAN) 1047 * ); 1048 * inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName(); 1049 * inOrder.verify(person.getAddress("the docks").getStreet()).getLongName(); 1050 * inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName(); 1051 * inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName(); 1052 * </code></pre> 1053 * </p> 1054 * 1055 * <p> 1056 * How deep stub work internally? 1057 * <pre class="code"><code class="java"> 1058 * //this: 1059 * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS); 1060 * when(mock.getBar().getName(), "deep"); 1061 * 1062 * //is equivalent of 1063 * Foo foo = mock(Foo.class); 1064 * Bar bar = mock(Bar.class); 1065 * when(foo.getBar()).thenReturn(bar); 1066 * when(bar.getName()).thenReturn("deep"); 1067 * </code></pre> 1068 * </p> 1069 * 1070 * <p> 1071 * This feature will not work when any return type of methods included in the chain cannot be mocked 1072 * (for example: is a primitive or a final class). This is because of java type system. 1073 * </p> 1074 */ 1075 public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS.get(); 1076 1077 /** 1078 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)} 1079 * <p> 1080 * {@link Answer} can be used to define the return values of unstubbed invocations. 1081 * <p> 1082 * This implementation can be helpful when working with legacy code. 1083 * When this implementation is used, unstubbed methods will delegate to the real implementation. 1084 * This is a way to create a partial mock object that calls real methods by default. 1085 * <p> 1086 * As usual you are going to read <b>the partial mock warning</b>: 1087 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. 1088 * How does partial mock fit into this paradigm? Well, it just doesn't... 1089 * Partial mock usually means that the complexity has been moved to a different method on the same object. 1090 * In most cases, this is not the way you want to design your application. 1091 * <p> 1092 * However, there are rare cases when partial mocks come handy: 1093 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) 1094 * However, I wouldn't use partial mocks for new, test-driven & well-designed code. 1095 * <p> 1096 * Example: 1097 * <pre class="code"><code class="java"> 1098 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS); 1099 * 1100 * // this calls the real implementation of Foo.getSomething() 1101 * value = mock.getSomething(); 1102 * 1103 * when(mock.getSomething()).thenReturn(fakeValue); 1104 * 1105 * // now fakeValue is returned 1106 * value = mock.getSomething(); 1107 * </code></pre> 1108 */ 1109 public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS.get(); 1110 1111 /** 1112 * Creates mock object of given class or interface. 1113 * <p> 1114 * See examples in javadoc for {@link Mockito} class 1115 * 1116 * @param classToMock class or interface to mock 1117 * @return mock object 1118 */ 1119 public static <T> T mock(Class<T> classToMock) { 1120 return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS)); 1121 } 1122 1123 /** 1124 * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors. 1125 * <p> 1126 * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. 1127 * <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. 1128 * <p> 1129 * <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.} 1130 * <p> 1131 * 1132 * See examples in javadoc for {@link Mockito} class 1133 * 1134 * @param classToMock class or interface to mock 1135 * @param name of the mock 1136 * @return mock object 1137 */ 1138 public static <T> T mock(Class<T> classToMock, String name) { 1139 return mock(classToMock, withSettings() 1140 .name(name) 1141 .defaultAnswer(RETURNS_DEFAULTS)); 1142 } 1143 1144 /** 1145 * Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information. 1146 * Can be used to find out if given object is a Mockito mock 1147 * or to find out if a given mock is a spy or mock. 1148 * <p> 1149 * In future Mockito versions MockingDetails may grow and provide other useful information about the mock, 1150 * e.g. invocations, stubbing info, etc. 1151 * 1152 * @param toInspect - object to inspect 1153 * @return A {@link org.mockito.MockingDetails} instance. 1154 * @since 1.9.5 1155 */ 1156 @Incubating 1157 public static MockingDetails mockingDetails(Object toInspect) { 1158 return MOCKITO_CORE.mockingDetails(toInspect); 1159 } 1160 1161 /** 1162 * <b>Deprecated : Please use mock(Foo.class, defaultAnswer);</b> 1163 * <p> 1164 * See {@link Mockito#mock(Class, Answer)} 1165 * <p> 1166 * Why it is deprecated? ReturnValues is being replaced by Answer 1167 * for better consistency & interoperability of the framework. 1168 * Answer interface has been in Mockito for a while and it has the same responsibility as ReturnValues. 1169 * There's no point in mainting exactly the same interfaces. 1170 * <p> 1171 * Creates mock with a specified strategy for its return values. 1172 * It's quite advanced feature and typically you don't need it to write decent tests. 1173 * However it can be helpful when working with legacy systems. 1174 * <p> 1175 * Obviously return values are used only when you don't stub the method call. 1176 * 1177 * <pre class="code"><code class="java"> 1178 * Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS); 1179 * Foo mockTwo = mock(Foo.class, new YourOwnReturnValues()); 1180 * </code></pre> 1181 * 1182 * <p>See examples in javadoc for {@link Mockito} class</p> 1183 * 1184 * @param classToMock class or interface to mock 1185 * @param returnValues default return values for unstubbed methods 1186 * 1187 * @return mock object 1188 * 1189 * @deprecated <b>Please use mock(Foo.class, defaultAnswer);</b> 1190 */ 1191 @Deprecated 1192 public static <T> T mock(Class<T> classToMock, ReturnValues returnValues) { 1193 return mock(classToMock, withSettings().defaultAnswer(new AnswerReturnValuesAdapter(returnValues))); 1194 } 1195 1196 /** 1197 * Creates mock with a specified strategy for its answers to interactions. 1198 * It's quite advanced feature and typically you don't need it to write decent tests. 1199 * However it can be helpful when working with legacy systems. 1200 * <p> 1201 * It is the default answer so it will be used <b>only when you don't</b> stub the method call. 1202 * 1203 * <pre class="code"><code class="java"> 1204 * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS); 1205 * Foo mockTwo = mock(Foo.class, new YourOwnAnswer()); 1206 * </code></pre> 1207 * 1208 * <p>See examples in javadoc for {@link Mockito} class</p> 1209 * 1210 * @param classToMock class or interface to mock 1211 * @param defaultAnswer default answer for unstubbed methods 1212 * 1213 * @return mock object 1214 */ 1215 public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) { 1216 return mock(classToMock, withSettings().defaultAnswer(defaultAnswer)); 1217 } 1218 1219 /** 1220 * Creates a mock with some non-standard settings. 1221 * <p> 1222 * The number of configuration points for a mock grows 1223 * so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods. 1224 * Hence {@link MockSettings}. 1225 * <pre class="code"><code class="java"> 1226 * Listener mock = mock(Listener.class, withSettings() 1227 * .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); 1228 * ); 1229 * </code></pre> 1230 * <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks? 1231 * Is the code under test so complicated that it requires non-standard mocks? 1232 * Wouldn't you prefer to refactor the code under test so it is testable in a simple way? 1233 * <p> 1234 * See also {@link Mockito#withSettings()} 1235 * <p> 1236 * See examples in javadoc for {@link Mockito} class 1237 * 1238 * @param classToMock class or interface to mock 1239 * @param mockSettings additional mock settings 1240 * @return mock object 1241 */ 1242 public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) { 1243 return MOCKITO_CORE.mock(classToMock, mockSettings); 1244 } 1245 1246 /** 1247 * Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed. 1248 * <p> 1249 * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code. 1250 * <p> 1251 * As usual you are going to read <b>the partial mock warning</b>: 1252 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. 1253 * How does partial mock fit into this paradigm? Well, it just doesn't... 1254 * Partial mock usually means that the complexity has been moved to a different method on the same object. 1255 * In most cases, this is not the way you want to design your application. 1256 * <p> 1257 * However, there are rare cases when partial mocks come handy: 1258 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) 1259 * However, I wouldn't use partial mocks for new, test-driven & well-designed code. 1260 * <p> 1261 * Example: 1262 * 1263 * <pre class="code"><code class="java"> 1264 * List list = new LinkedList(); 1265 * List spy = spy(list); 1266 * 1267 * //optionally, you can stub out some methods: 1268 * when(spy.size()).thenReturn(100); 1269 * 1270 * //using the spy calls <b>real</b> methods 1271 * spy.add("one"); 1272 * spy.add("two"); 1273 * 1274 * //prints "one" - the first element of a list 1275 * System.out.println(spy.get(0)); 1276 * 1277 * //size() method was stubbed - 100 is printed 1278 * System.out.println(spy.size()); 1279 * 1280 * //optionally, you can verify 1281 * verify(spy).add("one"); 1282 * verify(spy).add("two"); 1283 * </code></pre> 1284 * 1285 * <h4>Important gotcha on spying real objects!</h4> 1286 * <ol> 1287 * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies. 1288 * Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code> 1289 * family of methods for stubbing. Example: 1290 * 1291 * <pre class="code"><code class="java"> 1292 * List list = new LinkedList(); 1293 * List spy = spy(list); 1294 * 1295 * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) 1296 * when(spy.get(0)).thenReturn("foo"); 1297 * 1298 * //You have to use doReturn() for stubbing 1299 * doReturn("foo").when(spy).get(0); 1300 * </code></pre> 1301 * </li> 1302 * 1303 * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it. 1304 * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction 1305 * and their effect on real instance state. 1306 * 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>, 1307 * you won't see any effects on the real instance.</li> 1308 * 1309 * <li>Watch out for final methods. 1310 * 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. 1311 * Also you won't be able to verify those method as well. 1312 * </li> 1313 * </ol> 1314 * <p> 1315 * See examples in javadoc for {@link Mockito} class 1316 * 1317 * @param object 1318 * to spy on 1319 * @return a spy of the real object 1320 */ 1321 public static <T> T spy(T object) { 1322 return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings() 1323 .spiedInstance(object) 1324 .defaultAnswer(CALLS_REAL_METHODS)); 1325 } 1326 1327 /** 1328 * Stubs a method call with return value or an exception. E.g: 1329 * 1330 * <pre class="code"><code class="java"> 1331 * stub(mock.someMethod()).toReturn(10); 1332 * 1333 * //you can use flexible argument matchers, e.g: 1334 * stub(mock.someMethod(<b>anyString()</b>)).toReturn(10); 1335 * 1336 * //setting exception to be thrown: 1337 * stub(mock.someMethod("some arg")).toThrow(new RuntimeException()); 1338 * 1339 * //you can stub with different behavior for consecutive method calls. 1340 * //Last stubbing (e.g: toReturn("foo")) determines the behavior for further consecutive calls. 1341 * stub(mock.someMethod("some arg")) 1342 * .toThrow(new RuntimeException()) 1343 * .toReturn("foo"); 1344 * </code></pre> 1345 * <p> 1346 * Some users find stub() confusing therefore {@link Mockito#when(Object)} is recommended over stub() 1347 * <pre class="code"><code class="java"> 1348 * //Instead of: 1349 * stub(mock.count()).toReturn(10); 1350 * 1351 * //You can do: 1352 * when(mock.count()).thenReturn(10); 1353 * </code></pre> 1354 * For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable)} 1355 * <p> 1356 * Stubbing can be overridden: for example common stubbing can go to fixture 1357 * setup but the test methods can override it. 1358 * Please note that overridding stubbing is a potential code smell that points out too much stubbing. 1359 * <p> 1360 * Once stubbed, the method will always return stubbed value regardless 1361 * of how many times it is called. 1362 * <p> 1363 * Last stubbing is more important - when you stubbed the same method with 1364 * the same arguments many times. 1365 * <p> 1366 * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>. 1367 * Let's say you've stubbed foo.bar(). 1368 * If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed). 1369 * If your code doesn't care what get(0) returns then it should not be stubbed. 1370 * Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>. 1371 * 1372 * @param methodCall 1373 * method call 1374 * @return DeprecatedOngoingStubbing object to set stubbed value/exception 1375 */ 1376 public static <T> DeprecatedOngoingStubbing<T> stub(T methodCall) { 1377 return MOCKITO_CORE.stub(methodCall); 1378 } 1379 1380 /** 1381 * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called. 1382 * <p> 1383 * Simply put: "<b>When</b> the x method is called <b>then</b> return y". 1384 * <p> 1385 * <b>when() is a successor of deprecated {@link Mockito#stub(Object)}</b> 1386 * <p> 1387 * Examples: 1388 * 1389 * <pre class="code"><code class="java"> 1390 * <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10); 1391 * 1392 * //you can use flexible argument matchers, e.g: 1393 * when(mock.someMethod(<b>anyString()</b>)).thenReturn(10); 1394 * 1395 * //setting exception to be thrown: 1396 * when(mock.someMethod("some arg")).thenThrow(new RuntimeException()); 1397 * 1398 * //you can set different behavior for consecutive method calls. 1399 * //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls. 1400 * when(mock.someMethod("some arg")) 1401 * .thenThrow(new RuntimeException()) 1402 * .thenReturn("foo"); 1403 * 1404 * //Alternative, shorter version for consecutive stubbing: 1405 * when(mock.someMethod("some arg")) 1406 * .thenReturn("one", "two"); 1407 * //is the same as: 1408 * when(mock.someMethod("some arg")) 1409 * .thenReturn("one") 1410 * .thenReturn("two"); 1411 * 1412 * //shorter version for consecutive method calls throwing exceptions: 1413 * when(mock.someMethod("some arg")) 1414 * .thenThrow(new RuntimeException(), new NullPointerException(); 1415 * 1416 * </code></pre> 1417 * 1418 * For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable)} 1419 * <p> 1420 * Stubbing can be overridden: for example common stubbing can go to fixture 1421 * setup but the test methods can override it. 1422 * Please note that overridding stubbing is a potential code smell that points out too much stubbing. 1423 * <p> 1424 * Once stubbed, the method will always return stubbed value regardless 1425 * of how many times it is called. 1426 * <p> 1427 * Last stubbing is more important - when you stubbed the same method with 1428 * the same arguments many times. 1429 * <p> 1430 * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>. 1431 * Let's say you've stubbed <code>foo.bar()</code>. 1432 * If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed). 1433 * If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed. 1434 * Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>. 1435 * 1436 * <p> 1437 * See examples in javadoc for {@link Mockito} class 1438 * @param methodCall method to be stubbed 1439 * @return OngoingStubbing object used to stub fluently. 1440 * <strong>Do not</strong> create a reference to this returned object. 1441 */ 1442 public static <T> OngoingStubbing<T> when(T methodCall) { 1443 return MOCKITO_CORE.when(methodCall); 1444 } 1445 1446 /** 1447 * Verifies certain behavior <b>happened once</b>. 1448 * <p> 1449 * Alias to <code>verify(mock, times(1))</code> E.g: 1450 * <pre class="code"><code class="java"> 1451 * verify(mock).someMethod("some arg"); 1452 * </code></pre> 1453 * Above is equivalent to: 1454 * <pre class="code"><code class="java"> 1455 * verify(mock, times(1)).someMethod("some arg"); 1456 * </code></pre> 1457 * <p> 1458 * Arguments passed are compared using <code>equals()</code> method. 1459 * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed. 1460 * <p> 1461 * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>. 1462 * Let's say you've stubbed <code>foo.bar()</code>. 1463 * If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed). 1464 * If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed. 1465 * Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>. 1466 * 1467 * <p> 1468 * See examples in javadoc for {@link Mockito} class 1469 * 1470 * @param mock to be verified 1471 * @return mock object itself 1472 */ 1473 public static <T> T verify(T mock) { 1474 return MOCKITO_CORE.verify(mock, times(1)); 1475 } 1476 1477 /** 1478 * Verifies certain behavior happened at least once / exact number of times / never. E.g: 1479 * <pre class="code"><code class="java"> 1480 * verify(mock, times(5)).someMethod("was called five times"); 1481 * 1482 * verify(mock, atLeast(2)).someMethod("was called at least two times"); 1483 * 1484 * //you can use flexible argument matchers, e.g: 1485 * verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>); 1486 * </code></pre> 1487 * 1488 * <b>times(1) is the default</b> and can be omitted 1489 * <p> 1490 * Arguments passed are compared using <code>equals()</code> method. 1491 * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed. 1492 * <p> 1493 * 1494 * @param mock to be verified 1495 * @param mode times(x), atLeastOnce() or never() 1496 * 1497 * @return mock object itself 1498 */ 1499 public static <T> T verify(T mock, VerificationMode mode) { 1500 return MOCKITO_CORE.verify(mock, mode); 1501 } 1502 1503 /** 1504 * Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. 1505 * Normally, you don't need to reset your mocks, just create new mocks for each test method. 1506 * <p> 1507 * Instead of <code>#reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests. 1508 * <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. 1509 * Follow the whisper of your test methods: "Please keep us small & focused on single behavior". 1510 * There are several threads about it on mockito mailing list. 1511 * <p> 1512 * The only reason we added <code>reset()</code> method is to 1513 * make it possible to work with container-injected mocks. 1514 * See issue 55 (<a href="http://code.google.com/p/mockito/issues/detail?id=55">here</a>) 1515 * or FAQ (<a href="http://code.google.com/p/mockito/wiki/FAQ">here</a>). 1516 * <p> 1517 * <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). 1518 * <pre class="code"><code class="java"> 1519 * List mock = mock(List.class); 1520 * when(mock.size()).thenReturn(10); 1521 * mock.add(1); 1522 * 1523 * reset(mock); 1524 * //at this point the mock forgot any interactions & stubbing 1525 * </code></pre> 1526 * 1527 * @param <T> The Type of the mocks 1528 * @param mocks to be reset 1529 */ 1530 public static <T> void reset(T ... mocks) { 1531 MOCKITO_CORE.reset(mocks); 1532 } 1533 1534 /** 1535 * Checks if any of given mocks has any unverified interaction. 1536 * <p> 1537 * You can use this method after you verified your mocks - to make sure that nothing 1538 * else was invoked on your mocks. 1539 * <p> 1540 * See also {@link Mockito#never()} - it is more explicit and communicates the intent well. 1541 * <p> 1542 * Stubbed invocations (if called) are also treated as interactions. 1543 * <p> 1544 * A word of <b>warning</b>: 1545 * 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. 1546 * <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method. 1547 * <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant. 1548 * Abusing it leads to overspecified, less maintainable tests. You can find further reading 1549 * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>. 1550 * <p> 1551 * This method will also detect unverified invocations that occurred before the test method, 1552 * for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor. 1553 * Consider writing nice code that makes interactions only in test methods. 1554 * 1555 * <p> 1556 * Example: 1557 * 1558 * <pre class="code"><code class="java"> 1559 * //interactions 1560 * mock.doSomething(); 1561 * mock.doSomethingUnexpected(); 1562 * 1563 * //verification 1564 * verify(mock).doSomething(); 1565 * 1566 * //following will fail because 'doSomethingUnexpected()' is unexpected 1567 * verifyNoMoreInteractions(mock); 1568 * 1569 * </code></pre> 1570 * 1571 * See examples in javadoc for {@link Mockito} class 1572 * 1573 * @param mocks to be verified 1574 */ 1575 public static void verifyNoMoreInteractions(Object... mocks) { 1576 MOCKITO_CORE.verifyNoMoreInteractions(mocks); 1577 } 1578 1579 /** 1580 * Verifies that no interactions happened on given mocks. 1581 * <pre class="code"><code class="java"> 1582 * verifyZeroInteractions(mockOne, mockTwo); 1583 * </code></pre> 1584 * This method will also detect invocations 1585 * that occurred before the test method, for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor. 1586 * Consider writing nice code that makes interactions only in test methods. 1587 * <p> 1588 * See also {@link Mockito#never()} - it is more explicit and communicates the intent well. 1589 * <p> 1590 * See examples in javadoc for {@link Mockito} class 1591 * 1592 * @param mocks to be verified 1593 */ 1594 public static void verifyZeroInteractions(Object... mocks) { 1595 MOCKITO_CORE.verifyNoMoreInteractions(mocks); 1596 } 1597 1598 /** 1599 * <pre class="code"><code class="java"> 1600 * //Instead of: 1601 * stubVoid(mock).toThrow(e).on().someVoidMethod(); 1602 * 1603 * //Please do: 1604 * doThrow(e).when(mock).someVoidMethod(); 1605 * </code></pre> 1606 * 1607 * doThrow() replaces stubVoid() because of improved readability and consistency with the family of doAnswer() methods. 1608 * <p> 1609 * Originally, <code>stubVoid()</code> was used for stubbing void methods with exceptions. E.g: 1610 * 1611 * <pre class="code"><code class="java"> 1612 * stubVoid(mock).toThrow(new RuntimeException()).on().someMethod(); 1613 * 1614 * //you can stub with different behavior for consecutive calls. 1615 * //Last stubbing (e.g. toReturn()) determines the behavior for further consecutive calls. 1616 * stubVoid(mock) 1617 * .toThrow(new RuntimeException()) 1618 * .toReturn() 1619 * .on().someMethod(); 1620 * </code></pre> 1621 * 1622 * See examples in javadoc for {@link Mockito} class 1623 * 1624 * @deprecated Use {@link Mockito#doThrow(Throwable)} method for stubbing voids 1625 * 1626 * @param mock 1627 * to stub 1628 * @return stubbable object that allows stubbing with throwable 1629 */ 1630 public static <T> VoidMethodStubbable<T> stubVoid(T mock) { 1631 return MOCKITO_CORE.stubVoid(mock); 1632 } 1633 1634 /** 1635 * Use <code>doThrow()</code> when you want to stub the void method with an exception. 1636 * <p> 1637 * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... 1638 * <p> 1639 * Example: 1640 * 1641 * <pre class="code"><code class="java"> 1642 * doThrow(new RuntimeException()).when(mock).someVoidMethod(); 1643 * </code></pre> 1644 * 1645 * @param toBeThrown to be thrown when the stubbed method is called 1646 * @return stubber - to select a method for stubbing 1647 */ 1648 public static Stubber doThrow(Throwable toBeThrown) { 1649 return MOCKITO_CORE.doAnswer(new ThrowsException(toBeThrown)); 1650 } 1651 1652 /** 1653 * Use <code>doThrow()</code> when you want to stub the void method to throw exception of specified class. 1654 * <p> 1655 * A new exception instance will be created for each method invocation. 1656 * <p> 1657 * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... 1658 * <p> 1659 * Example: 1660 * 1661 * <pre class="code"><code class="java"> 1662 * doThrow(RuntimeException.class).when(mock).someVoidMethod(); 1663 * </code></pre> 1664 * 1665 * @param toBeThrown to be thrown when the stubbed method is called 1666 * @return stubber - to select a method for stubbing 1667 * @since 1.9.0 1668 */ 1669 public static Stubber doThrow(Class<? extends Throwable> toBeThrown) { 1670 return MOCKITO_CORE.doAnswer(new ThrowsExceptionClass(toBeThrown)); 1671 } 1672 1673 1674 /** 1675 * Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method. 1676 * <p> 1677 * As usual you are going to read <b>the partial mock warning</b>: 1678 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. 1679 * How does partial mock fit into this paradigm? Well, it just doesn't... 1680 * Partial mock usually means that the complexity has been moved to a different method on the same object. 1681 * In most cases, this is not the way you want to design your application. 1682 * <p> 1683 * However, there are rare cases when partial mocks come handy: 1684 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) 1685 * However, I wouldn't use partial mocks for new, test-driven & well-designed code. 1686 * <p> 1687 * See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks. 1688 * <b>Mockito.spy() is a recommended way of creating partial mocks.</b> 1689 * 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. 1690 * <p> 1691 * Example: 1692 * <pre class="code"><code class="java"> 1693 * Foo mock = mock(Foo.class); 1694 * doCallRealMethod().when(mock).someVoidMethod(); 1695 * 1696 * // this will call the real implementation of Foo.someVoidMethod() 1697 * mock.someVoidMethod(); 1698 * </code></pre> 1699 * <p> 1700 * See examples in javadoc for {@link Mockito} class 1701 * 1702 * @return stubber - to select a method for stubbing 1703 * @since 1.9.5 1704 */ 1705 public static Stubber doCallRealMethod() { 1706 return MOCKITO_CORE.doAnswer(new CallsRealMethods()); 1707 } 1708 1709 /** 1710 * Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}. 1711 * <p> 1712 * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... 1713 * <p> 1714 * Example: 1715 * 1716 * <pre class="code"><code class="java"> 1717 * doAnswer(new Answer() { 1718 * public Object answer(InvocationOnMock invocation) { 1719 * Object[] args = invocation.getArguments(); 1720 * Mock mock = invocation.getMock(); 1721 * return null; 1722 * }}) 1723 * .when(mock).someMethod(); 1724 * </code></pre> 1725 * <p> 1726 * See examples in javadoc for {@link Mockito} class 1727 * 1728 * @param answer to answer when the stubbed method is called 1729 * @return stubber - to select a method for stubbing 1730 */ 1731 public static Stubber doAnswer(Answer answer) { 1732 return MOCKITO_CORE.doAnswer(answer); 1733 } 1734 1735 /** 1736 * Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b> 1737 * However, there are rare situations when doNothing() comes handy: 1738 * <p> 1739 * <ol> 1740 * <li>Stubbing consecutive calls on a void method: 1741 * <pre class="code"><code class="java"> 1742 * doNothing(). 1743 * doThrow(new RuntimeException()) 1744 * .when(mock).someVoidMethod(); 1745 * 1746 * //does nothing the first time: 1747 * mock.someVoidMethod(); 1748 * 1749 * //throws RuntimeException the next time: 1750 * mock.someVoidMethod(); 1751 * </code></pre> 1752 * </li> 1753 * <li>When you spy real objects and you want the void method to do nothing: 1754 * <pre class="code"><code class="java"> 1755 * List list = new LinkedList(); 1756 * List spy = spy(list); 1757 * 1758 * //let's make clear() do nothing 1759 * doNothing().when(spy).clear(); 1760 * 1761 * spy.add("one"); 1762 * 1763 * //clear() does nothing, so the list still contains "one" 1764 * spy.clear(); 1765 * </code></pre> 1766 * </li> 1767 * </ol> 1768 * <p> 1769 * See examples in javadoc for {@link Mockito} class 1770 * 1771 * @return stubber - to select a method for stubbing 1772 */ 1773 public static Stubber doNothing() { 1774 return MOCKITO_CORE.doAnswer(new DoesNothing()); 1775 } 1776 1777 /** 1778 * Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}. 1779 * <p> 1780 * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe 1781 * and more readable</b> (especially when stubbing consecutive calls). 1782 * <p> 1783 * Here are those rare occasions when doReturn() comes handy: 1784 * <p> 1785 * 1786 * <ol> 1787 * <li>When spying real objects and calling real methods on a spy brings side effects 1788 * 1789 * <pre class="code"><code class="java"> 1790 * List list = new LinkedList(); 1791 * List spy = spy(list); 1792 * 1793 * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) 1794 * when(spy.get(0)).thenReturn("foo"); 1795 * 1796 * //You have to use doReturn() for stubbing: 1797 * doReturn("foo").when(spy).get(0); 1798 * </code></pre> 1799 * </li> 1800 * 1801 * <li>Overriding a previous exception-stubbing: 1802 * <pre class="code"><code class="java"> 1803 * when(mock.foo()).thenThrow(new RuntimeException()); 1804 * 1805 * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. 1806 * when(mock.foo()).thenReturn("bar"); 1807 * 1808 * //You have to use doReturn() for stubbing: 1809 * doReturn("bar").when(mock).foo(); 1810 * </code></pre> 1811 * </li> 1812 * </ol> 1813 * 1814 * Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. 1815 * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general 1816 * overridding stubbing is a potential code smell that points out too much stubbing. 1817 * <p> 1818 * See examples in javadoc for {@link Mockito} class 1819 * 1820 * @param toBeReturned to be returned when the stubbed method is called 1821 * @return stubber - to select a method for stubbing 1822 */ 1823 public static Stubber doReturn(Object toBeReturned) { 1824 return MOCKITO_CORE.doAnswer(new Returns(toBeReturned)); 1825 } 1826 1827 /** 1828 * Creates {@link org.mockito.InOrder} object that allows verifying mocks in order. 1829 * 1830 * <pre class="code"><code class="java"> 1831 * InOrder inOrder = inOrder(firstMock, secondMock); 1832 * 1833 * inOrder.verify(firstMock).add("was called first"); 1834 * inOrder.verify(secondMock).add("was called second"); 1835 * </code></pre> 1836 * 1837 * Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one 1838 * but only those that you are interested in testing in order. 1839 * <p> 1840 * Also, you can create InOrder object passing only mocks that are relevant for in-order verification. 1841 * <p> 1842 * <code>InOrder</code> verification is 'greedy'. You will hardly every notice it but 1843 * if you want to find out more search for 'greedy' on the Mockito 1844 * <a href="http://code.google.com/p/mockito/w/list">wiki pages</a>. 1845 * <p> 1846 * As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()} 1847 * <p> 1848 * See examples in javadoc for {@link Mockito} class 1849 * 1850 * @param mocks to be verified in order 1851 * 1852 * @return InOrder object to be used to verify in order 1853 */ 1854 public static InOrder inOrder(Object... mocks) { 1855 return MOCKITO_CORE.inOrder(mocks); 1856 } 1857 1858 /** 1859 * Ignores stubbed methods of given mocks for the sake of verification. 1860 * Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>. 1861 * Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs. 1862 * <p> 1863 * <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code> 1864 * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code> 1865 * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)} 1866 * 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(). 1867 * <p> 1868 * This method <b>changes the input mocks</b>! This method returns input mocks just for convenience. 1869 * <p> 1870 * Ignored stubs will also be ignored for verification inOrder, including {@link org.mockito.InOrder#verifyNoMoreInteractions()}. 1871 * See the second example. 1872 * <p> 1873 * Example: 1874 * <pre class="code"><code class="java"> 1875 * //mocking lists for the sake of the example (if you mock List in real you will burn in hell) 1876 * List mock1 = mock(List.class), mock2 = mock(List.class); 1877 * 1878 * //stubbing mocks: 1879 * when(mock1.get(0)).thenReturn(10); 1880 * when(mock2.get(0)).thenReturn(20); 1881 * 1882 * //using mocks by calling stubbed get(0) methods: 1883 * System.out.println(mock1.get(0)); //prints 10 1884 * System.out.println(mock2.get(0)); //prints 20 1885 * 1886 * //using mocks by calling clear() methods: 1887 * mock1.clear(); 1888 * mock2.clear(); 1889 * 1890 * //verification: 1891 * verify(mock1).clear(); 1892 * verify(mock2).clear(); 1893 * 1894 * //verifyNoMoreInteractions() fails because get() methods were not accounted for. 1895 * try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e); 1896 * 1897 * //However, if we ignore stubbed methods then we can verifyNoMoreInteractions() 1898 * verifyNoMoreInteractions(ignoreStubs(mock1, mock2)); 1899 * 1900 * //Remember that ignoreStubs() <b>*changes*</b> the input mocks and returns them for convenience. 1901 * </code></pre> 1902 * Ignoring stubs can be used with <b>verification in order</b>: 1903 * <pre class="code"><code class="java"> 1904 * List list = mock(List.class); 1905 * when(mock.get(0)).thenReturn("foo"); 1906 * 1907 * list.add(0); 1908 * System.out.println(list.get(0)); //we don't want to verify this 1909 * list.clear(); 1910 * 1911 * InOrder inOrder = inOrder(ignoreStubs(list)); 1912 * inOrder.verify(list).add(0); 1913 * inOrder.verify(list).clear(); 1914 * inOrder.verifyNoMoreInteractions(); 1915 * </code></pre> 1916 * 1917 * @since 1.9.0 1918 * @param mocks input mocks that will be changed 1919 * @return the same mocks that were passed in as parameters 1920 */ 1921 public static Object[] ignoreStubs(Object... mocks) { 1922 return MOCKITO_CORE.ignoreStubs(mocks); 1923 } 1924 1925 /** 1926 * Allows verifying exact number of invocations. E.g: 1927 * <pre class="code"><code class="java"> 1928 * verify(mock, times(2)).someMethod("some arg"); 1929 * </code></pre> 1930 * 1931 * See examples in javadoc for {@link Mockito} class 1932 * 1933 * @param wantedNumberOfInvocations wanted number of invocations 1934 * 1935 * @return verification mode 1936 */ 1937 public static VerificationMode times(int wantedNumberOfInvocations) { 1938 return VerificationModeFactory.times(wantedNumberOfInvocations); 1939 } 1940 1941 /** 1942 * Alias to <code>times(0)</code>, see {@link Mockito#times(int)} 1943 * <p> 1944 * Verifies that interaction did not happen. E.g: 1945 * <pre class="code"><code class="java"> 1946 * verify(mock, never()).someMethod(); 1947 * </code></pre> 1948 * 1949 * <p> 1950 * If you want to verify there were NO interactions with the mock 1951 * check out {@link Mockito#verifyZeroInteractions(Object...)} 1952 * or {@link Mockito#verifyNoMoreInteractions(Object...)} 1953 * <p> 1954 * See examples in javadoc for {@link Mockito} class 1955 * 1956 * @return verification mode 1957 */ 1958 public static VerificationMode never() { 1959 return times(0); 1960 } 1961 1962 /** 1963 * Allows at-least-once verification. E.g: 1964 * <pre class="code"><code class="java"> 1965 * verify(mock, atLeastOnce()).someMethod("some arg"); 1966 * </code></pre> 1967 * Alias to <code>atLeast(1)</code>. 1968 * <p> 1969 * See examples in javadoc for {@link Mockito} class 1970 * 1971 * @return verification mode 1972 */ 1973 public static VerificationMode atLeastOnce() { 1974 return VerificationModeFactory.atLeastOnce(); 1975 } 1976 1977 /** 1978 * Allows at-least-x verification. E.g: 1979 * <pre class="code"><code class="java"> 1980 * verify(mock, atLeast(3)).someMethod("some arg"); 1981 * </code></pre> 1982 * 1983 * See examples in javadoc for {@link Mockito} class 1984 * 1985 * @param minNumberOfInvocations minimum number of invocations 1986 * 1987 * @return verification mode 1988 */ 1989 public static VerificationMode atLeast(int minNumberOfInvocations) { 1990 return VerificationModeFactory.atLeast(minNumberOfInvocations); 1991 } 1992 1993 /** 1994 * Allows at-most-x verification. E.g: 1995 * <pre class="code"><code class="java"> 1996 * verify(mock, atMost(3)).someMethod("some arg"); 1997 * </code></pre> 1998 * 1999 * See examples in javadoc for {@link Mockito} class 2000 * 2001 * @param maxNumberOfInvocations max number of invocations 2002 * 2003 * @return verification mode 2004 */ 2005 public static VerificationMode atMost(int maxNumberOfInvocations) { 2006 return VerificationModeFactory.atMost(maxNumberOfInvocations); 2007 } 2008 2009 /** 2010 * Allows non-greedy verification in order. For example 2011 * <pre class="code"><code class="java"> 2012 * inOrder.verify( mock, calls( 2 )).someMethod( "some arg" ); 2013 * </code></pre> 2014 * <ul> 2015 * <li>will not fail if the method is called 3 times, unlike times( 2 )</li> 2016 * <li>will not mark the third invocation as verified, unlike atLeast( 2 )</li> 2017 * </ul> 2018 * This verification mode can only be used with in order verification. 2019 * @param wantedNumberOfInvocations number of invocations to verify 2020 * @return verification mode 2021 */ 2022 public static VerificationMode calls( int wantedNumberOfInvocations ){ 2023 return VerificationModeFactory.calls( wantedNumberOfInvocations ); 2024 } 2025 2026 /** 2027 * Allows checking if given method was the only one invoked. E.g: 2028 * <pre class="code"><code class="java"> 2029 * verify(mock, only()).someMethod(); 2030 * //above is a shorthand for following 2 lines of code: 2031 * verify(mock).someMethod(); 2032 * verifyNoMoreInvocations(mock); 2033 * </code></pre> 2034 * 2035 * <p> 2036 * See also {@link Mockito#verifyNoMoreInteractions(Object...)} 2037 * <p> 2038 * See examples in javadoc for {@link Mockito} class 2039 * 2040 * @return verification mode 2041 */ 2042 public static VerificationMode only() { 2043 return VerificationModeFactory.only(); 2044 } 2045 2046 /** 2047 * Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired 2048 * interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent 2049 * conditions. 2050 * <p> 2051 * It feels this feature should be used rarely - figure out a better way of testing your multi-threaded system 2052 * <p> 2053 * Not yet implemented to work with InOrder verification. 2054 * <pre class="code"><code class="java"> 2055 * //passes when someMethod() is called within given time span 2056 * verify(mock, timeout(100)).someMethod(); 2057 * //above is an alias to: 2058 * verify(mock, timeout(100).times(1)).someMethod(); 2059 * 2060 * //passes when someMethod() is called <b>*exactly*</b> 2 times within given time span 2061 * verify(mock, timeout(100).times(2)).someMethod(); 2062 * 2063 * //passes when someMethod() is called <b>*at least*</b> 2 times within given time span 2064 * verify(mock, timeout(100).atLeast(2)).someMethod(); 2065 * 2066 * //verifies someMethod() within given time span using given verification mode 2067 * //useful only if you have your own custom verification modes. 2068 * verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod(); 2069 * </code></pre> 2070 * 2071 * See examples in javadoc for {@link Mockito} class 2072 * 2073 * @param millis - time span in millisecond 2074 * 2075 * @return verification mode 2076 */ 2077 public static VerificationWithTimeout timeout(int millis) { 2078 return new Timeout(millis, VerificationModeFactory.times(1)); 2079 } 2080 2081 /** 2082 * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: <a href="http://code.google.com/p/mockito/wiki/FAQ">http://code.google.com/p/mockito/wiki/FAQ</a> 2083 * <p> 2084 * 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> 2085 * <p> 2086 * <code>validateMockitoUsage()</code> <b>explicitly validates</b> the framework state to detect invalid use of Mockito. 2087 * However, this feature is optional <b>because Mockito validates the usage all the time...</b> but there is a gotcha so read on. 2088 * <p> 2089 * Examples of incorrect use: 2090 * <pre class="code"><code class="java"> 2091 * //Oups, someone forgot thenReturn() part: 2092 * when(mock.get()); 2093 * 2094 * //Oups, someone put the verified method call inside verify() where it should be outside: 2095 * verify(mock.execute()); 2096 * 2097 * //Oups, someone has used EasyMock for too long and forgot to specify the method to verify: 2098 * verify(mock); 2099 * </code></pre> 2100 * 2101 * Mockito throws exceptions if you misuse it so that you know if your tests are written correctly. 2102 * 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.). 2103 * But even though the exception might be thrown in the next test, 2104 * the exception <b>message contains a navigable stack trace element</b> with location of the defect. 2105 * Hence you can click and find the place where Mockito was misused. 2106 * <p> 2107 * Sometimes though, you might want to validate the framework usage explicitly. 2108 * For example, one of the users wanted to put <code>validateMockitoUsage()</code> in his <code>@After</code> method 2109 * so that he knows immediately when he misused Mockito. 2110 * Without it, he would have known about it not sooner than <b>next time</b> he used the framework. 2111 * One more benefit of having <code>validateMockitoUsage()</code> in <code>@After</code> is that jUnit runner will always fail in the test method with defect 2112 * whereas ordinary 'next-time' validation might fail the <b>next</b> test method. 2113 * But even though JUnit might report next test as red, don't worry about it 2114 * and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito. 2115 * <p> 2116 * <b>Built-in runner: {@link MockitoJUnitRunner}</b> does validateMockitoUsage() after each test method. 2117 * <p> 2118 * Bear in mind that <b>usually you don't have to <code>validateMockitoUsage()</code></b> 2119 * and framework validation triggered on next-time basis should be just enough, 2120 * mainly because of enhanced exception message with clickable location of defect. 2121 * However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure 2122 * (like your own runner or base class for all tests) because adding a special action to <code>@After</code> has zero cost. 2123 * <p> 2124 * See examples in javadoc for {@link Mockito} class 2125 */ 2126 public static void validateMockitoUsage() { 2127 MOCKITO_CORE.validateMockitoUsage(); 2128 } 2129 2130 /** 2131 * Allows mock creation with additional mock settings. 2132 * <p> 2133 * Don't use it too often. 2134 * Consider writing simple tests that use simple mocks. 2135 * Repeat after me: simple tests push simple, KISSy, readable & maintainable code. 2136 * If you cannot write a test in a simple way - refactor the code under test. 2137 * <p> 2138 * Examples of mock settings: 2139 * <pre class="code"><code class="java"> 2140 * //Creates mock with different default answer & name 2141 * Foo mock = mock(Foo.class, withSettings() 2142 * .defaultAnswer(RETURNS_SMART_NULLS) 2143 * .name("cool mockie")); 2144 * 2145 * //Creates mock with different default answer, descriptive name and extra interfaces 2146 * Foo mock = mock(Foo.class, withSettings() 2147 * .defaultAnswer(RETURNS_SMART_NULLS) 2148 * .name("cool mockie") 2149 * .extraInterfaces(Bar.class)); 2150 * </code></pre> 2151 * {@link MockSettings} has been introduced for two reasons. 2152 * Firstly, to make it easy to add another mock settings when the demand comes. 2153 * Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods. 2154 * <p> 2155 * See javadoc for {@link MockSettings} to learn about possible mock settings. 2156 * <p> 2157 * 2158 * @return mock settings instance with defaults. 2159 */ 2160 public static MockSettings withSettings() { 2161 return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS); 2162 } 2163 2164 /** 2165 * Helps debugging failing tests. Experimental - use at your own risk. We're not sure if this method will stay in public api. 2166 */ 2167 @Deprecated 2168 static MockitoDebugger debug() { 2169 return new MockitoDebuggerImpl(); 2170 } 2171} 2172