-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Mockito.java
3328 lines (3266 loc) · 151 KB
/
Mockito.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito;
import org.mockito.exceptions.misusing.PotentialStubbingProblem;
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
import org.mockito.internal.session.DefaultMockitoSessionBuilder;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationFactory;
import org.mockito.invocation.MockHandler;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
import org.mockito.listeners.VerificationStartedEvent;
import org.mockito.listeners.VerificationStartedListener;
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
import org.mockito.plugins.MockitoPlugins;
import org.mockito.quality.MockitoHint;
import org.mockito.quality.Strictness;
import org.mockito.session.MockitoSessionBuilder;
import org.mockito.session.MockitoSessionLogger;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.Answer1;
import org.mockito.stubbing.LenientStubber;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
import org.mockito.stubbing.VoidAnswer1;
import org.mockito.verification.*;
import java.util.function.Function;
/**
* <p align="left"><img src="logo.png" srcset="logo@2x.png 2x" alt="Mockito logo"/></p>
* The Mockito library enables mock creation, verification and stubbing.
*
* <p>
* This javadoc content is also available on the <a href="https://site.mockito.org/">https://site.mockito.org/</a> web page.
* All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code.
* It allows access to documentation straight from the IDE even if you work offline.
* It motivates Mockito developers to keep documentation up-to-date with the code that they write,
* every day, with every commit.
*
* <h1>Contents</h1>
*
* <b>
* <a href="#0">0. Migrating to Mockito 2</a><br/>
* <a href="#0.1">0.1 Mockito Android support</a></br/>
* <a href="#0.2">0.2 Configuration-free inline mock making</a></br/>
* <a href="#1">1. Let's verify some behaviour! </a><br/>
* <a href="#2">2. How about some stubbing? </a><br/>
* <a href="#3">3. Argument matchers </a><br/>
* <a href="#4">4. Verifying exact number of invocations / at least once / never </a><br/>
* <a href="#5">5. Stubbing void methods with exceptions </a><br/>
* <a href="#6">6. Verification in order </a><br/>
* <a href="#7">7. Making sure interaction(s) never happened on mock </a><br/>
* <a href="#8">8. Finding redundant invocations </a><br/>
* <a href="#9">9. Shorthand for mocks creation - <code>@Mock</code> annotation </a><br/>
* <a href="#10">10. Stubbing consecutive calls (iterator-style stubbing) </a><br/>
* <a href="#11">11. Stubbing with callbacks </a><br/>
* <a href="#12">12. <code>doReturn()</code>|<code>doThrow()</code>|<code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a><br/>
* <a href="#13">13. Spying on real objects </a><br/>
* <a href="#14">14. Changing default return values of unstubbed invocations (Since 1.7) </a><br/>
* <a href="#15">15. Capturing arguments for further assertions (Since 1.8.0) </a><br/>
* <a href="#16">16. Real partial mocks (Since 1.8.0) </a><br/>
* <a href="#17">17. Resetting mocks (Since 1.8.0) </a><br/>
* <a href="#18">18. Troubleshooting & validating framework usage (Since 1.8.0) </a><br/>
* <a href="#19">19. Aliases for behavior driven development (Since 1.8.0) </a><br/>
* <a href="#20">20. Serializable mocks (Since 1.8.1) </a><br/>
* <a href="#21">21. New annotations: <code>@Captor</code>, <code>@Spy</code>, <code>@InjectMocks</code> (Since 1.8.3) </a><br/>
* <a href="#22">22. Verification with timeout (Since 1.8.5) </a><br/>
* <a href="#23">23. Automatic instantiation of <code>@Spies</code>, <code>@InjectMocks</code> and constructor injection goodness (Since 1.9.0)</a><br/>
* <a href="#24">24. One-liner stubs (Since 1.9.0)</a><br/>
* <a href="#25">25. Verification ignoring stubs (Since 1.9.0)</a><br/>
* <a href="#26">26. Mocking details (Improved in 2.2.x)</a><br/>
* <a href="#27">27. Delegate calls to real instance (Since 1.9.5)</a><br/>
* <a href="#28">28. <code>MockMaker</code> API (Since 1.9.5)</a><br/>
* <a href="#29">29. BDD style verification (Since 1.10.0)</a><br/>
* <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a><br/>
* <a href="#31">31. Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3><br/>
* <a href="#32">32. Better generic support with deep stubs (Since 1.10.0)</a></h3><br/>
* <a href="#33">33. Mockito JUnit rule (Since 1.10.17)</a><br/>
* <a href="#34">34. Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a><br/>
* <a href="#35">35. Custom verification failure message (Since 2.1.0)</a><br/>
* <a href="#36">36. Java 8 Lambda Matcher Support (Since 2.1.0)</a><br/>
* <a href="#37">37. Java 8 Custom Answer Support (Since 2.1.0)</a><br/>
* <a href="#38">38. Meta data and generic type retention (Since 2.1.0)</a><br/>
* <a href="#39">39. Mocking final types, enums and final methods (Since 2.1.0)</a><br/>
* <a href="#40">40. Improved productivity and cleaner tests with "stricter" Mockito (Since 2.+)</a><br/>
* <a href="#41">41. Advanced public API for framework integrations (Since 2.10.+)</a><br/>
* <a href="#42">42. New API for integrations: listening on verification start events (Since 2.11.+)</a><br/>
* <a href="#43">43. New API for integrations: <code>MockitoSession</code> is usable by testing frameworks (Since 2.15.+)</a><br/>
* <a href="#44">44. Deprecated <code>org.mockito.plugins.InstantiatorProvider</code> as it was leaking internal API. it was replaced by <code>org.mockito.plugins.InstantiatorProvider2 (Since 2.15.4)</code></a><br/>
* <a href="#45">45. New JUnit Jupiter (JUnit5+) extension</a><br/>
* <a href="#46">46. New <code>Mockito.lenient()</code> and <code>MockSettings.lenient()</code> methods (Since 2.20.0)</a><br/>
* <a href="#47">47. New API for clearing mock state in inline mocking (Since 2.25.0)</a><br/>
* <a href="#48">48. New API for mocking static methods (Since 3.4.0)</a><br/>
* <a href="#49">49. New API for mocking object construction (Since 3.5.0)</a><br/>
* <a href="#50">50. Avoiding code generation when restricting mocks to interfaces (Since 3.12.2)</a><br/>
* </b>
*
* <h3 id="0">0. <a class="meaningful_link" href="#mockito2" name="mockito2">Migrating to Mockito 2</a></h3>
*
* In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0!
* Mockito follows <a href="https://semver.org/">semantic versioning</a> and contains breaking changes only on major version upgrades.
* In the lifecycle of a library, breaking changes are necessary
* to roll out a set of brand new features that alter the existing behavior or even change the API.
* For a comprehensive guide on the new release including incompatible changes,
* see '<a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2">What's new in Mockito 2</a>' wiki page.
* We hope that you enjoy Mockito 2!
*
* <h3 id="0.1">0.1. <a class="meaningful_link" href="#mockito-android" name="mockito-android">Mockito Android support</a></h3>
*
* With Mockito version 2.6.1 we ship "native" Android support. To enable Android support, add the `mockito-android` library as dependency
* to your project. This artifact is published to the same Mockito organization and can be imported for Android as follows:
*
* <pre class="code"><code>
* repositories {
* mavenCentral()
* }
* dependencies {
* testCompile "org.mockito:mockito-core:+"
* androidTestCompile "org.mockito:mockito-android:+"
* }
* </code></pre>
*
* You can continue to run the same unit tests on a regular VM by using the `mockito-core` artifact in your "testCompile" scope as shown
* above. Be aware that you cannot use the <a href="#39">inline mock maker</a> on Android due to limitations in the Android VM.
*
* If you encounter issues with mocking on Android, please open an issue
* <a href="https://github.com/mockito/mockito/issues/new">on the official issue tracker</a>.
* Do provide the version of Android you are working on and dependencies of your project.
*
* <h3 id="0.2">0.2. <a class="meaningful_link" href="#mockito-inline" name="mockito-inline">Configuration-free inline mock making</a></h3>
*
* Starting with version 2.7.6, we offer the 'mockito-inline' artifact that enables <a href="#39">inline mock making</a> without configuring
* the MockMaker extension file. To use this, add the `mockito-inline` instead of the `mockito-core` artifact as follows:
*
* <pre class="code"><code>
* repositories {
* mavenCentral()
* }
* dependencies {
* testCompile "org.mockito:mockito-inline:+"
* }
* </code></pre>
*
* Be aware that this artifact may be abolished when the inline mock making feature is integrated into the default mock maker.
*
* <p>
* For more information about inline mock making, see <a href="#39">section 39</a>.
*
* <h3 id="1">1. <a class="meaningful_link" href="#verification" name="verification">Let's verify some behaviour!</a></h3>
*
* The following examples mock a List, because most people are familiar with the interface (such as the
* <code>add()</code>, <code>get()</code>, <code>clear()</code> methods). <br>
* In reality, please don't mock the List class. Use a real instance instead.
*
* <pre class="code"><code class="java">
* //Let's import Mockito statically so that the code looks clearer
* import static org.mockito.Mockito.*;
*
* //mock creation
* List mockedList = mock(List.class);
*
* //using mock object
* mockedList.add("one");
* mockedList.clear();
*
* //verification
* verify(mockedList).add("one");
* verify(mockedList).clear();
* </code></pre>
*
* <p>
* Once created, a mock will remember all interactions. Then you can selectively
* verify whatever interactions you are interested in.
* </p>
*
*
*
* <h3 id="2">2. <a class="meaningful_link" href="#stubbing" name="stubbing">How about some stubbing?</a></h3>
*
* <pre class="code"><code class="java">
* //You can mock concrete classes, not just interfaces
* LinkedList mockedList = mock(LinkedList.class);
*
* //stubbing
* when(mockedList.get(0)).thenReturn("first");
* when(mockedList.get(1)).thenThrow(new RuntimeException());
*
* //following prints "first"
* System.out.println(mockedList.get(0));
*
* //following throws runtime exception
* System.out.println(mockedList.get(1));
*
* //following prints "null" because get(999) was not stubbed
* System.out.println(mockedList.get(999));
*
* //Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>
* //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
* //If your code doesn't care what get(0) returns, then it should not be stubbed.
* verify(mockedList).get(0);
* </code></pre>
*
* <ul>
* <li> By default, for all methods that return a value, a mock will return either null,
* a primitive/primitive wrapper value, or an empty collection, as appropriate.
* For example 0 for an int/Integer and false for a boolean/Boolean. </li>
*
* <li> Stubbing can be overridden: for example common stubbing can go to
* fixture setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing</li>
*
* <li> Once stubbed, the method will always return a stubbed value, regardless
* of how many times it is called. </li>
*
* <li> Last stubbing is more important - when you stubbed the same method with
* the same arguments many times.
* Other words: <b>the order of stubbing matters</b> but it is only meaningful rarely,
* e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.</li>
*
* </ul>
*
*
*
* <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers" name="argument_matchers">Argument matchers</a></h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* Sometimes, when extra flexibility is required then you might use argument matchers:
*
* <pre class="code"><code class="java">
* //stubbing using built-in anyInt() argument matcher
* when(mockedList.get(anyInt())).thenReturn("element");
*
* //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
* when(mockedList.contains(argThat(isValid()))).thenReturn(true);
*
* //following prints "element"
* System.out.println(mockedList.get(999));
*
* //<b>you can also verify using an argument matcher</b>
* verify(mockedList).get(anyInt());
*
* //<b>argument matchers can also be written as Java 8 Lambdas</b>
* verify(mockedList).add(argThat(someString -> someString.length() > 5));
*
* </code></pre>
*
* <p>
* Argument matchers allow flexible verification or stubbing.
* {@link ArgumentMatchers Click here} {@link org.mockito.hamcrest.MockitoHamcrest or here} to see more built-in matchers
* and examples of <b>custom argument matchers / hamcrest matchers</b>.
* <p>
* For information solely on <b>custom argument matchers</b> check out javadoc for {@link ArgumentMatcher} class.
* <p>
* Be reasonable with using complicated argument matching.
* The natural matching style using <code>equals()</code> with occasional <code>anyX()</code> matchers tend to give clean & simple tests.
* 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.
* <p>
* Also, read <a href="#15">section 15</a> or javadoc for {@link ArgumentCaptor} class.
* {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions.
* <p>
* <b>Warning on argument matchers:</b>
* <p>
* If you are using argument matchers, <b>all arguments</b> have to be provided
* by matchers.
* <p>
* The following example shows verification but the same applies to stubbing:
*
* <pre class="code"><code class="java">
* verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
* //above is correct - eq() is also an argument matcher
*
* verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
* //above is incorrect - exception will be thrown because third argument is given without an argument matcher.
* </code></pre>
*
* <p>
* Matcher methods like <code>any()</code>, <code>eq()</code> <b>do not</b> return matchers.
* Internally, they record a matcher on a stack and return a dummy value (usually null).
* This implementation is due to static type safety imposed by the java compiler.
* The consequence is that you cannot use <code>any()</code>, <code>eq()</code> methods outside of verified/stubbed method.
*
*
*
*
* <h3 id="4">4. <a class="meaningful_link" href="#exact_verification" name="exact_verification">Verifying exact number of invocations</a> /
* <a class="meaningful_link" href="#at_least_verification" name="at_least_verification">at least x</a> / never</h3>
*
* <pre class="code"><code class="java">
* //using mock
* mockedList.add("once");
*
* mockedList.add("twice");
* mockedList.add("twice");
*
* mockedList.add("three times");
* mockedList.add("three times");
* mockedList.add("three times");
*
* //following two verifications work exactly the same - times(1) is used by default
* verify(mockedList).add("once");
* verify(mockedList, times(1)).add("once");
*
* //exact number of invocations verification
* verify(mockedList, times(2)).add("twice");
* verify(mockedList, times(3)).add("three times");
*
* //verification using never(). never() is an alias to times(0)
* verify(mockedList, never()).add("never happened");
*
* //verification using atLeast()/atMost()
* verify(mockedList, atMostOnce()).add("once");
* verify(mockedList, atLeastOnce()).add("three times");
* verify(mockedList, atLeast(2)).add("three times");
* verify(mockedList, atMost(5)).add("three times");
*
* </code></pre>
*
* <p>
* <b>times(1) is the default.</b> Therefore using times(1) explicitly can be
* omitted.
*
*
*
*
* <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions" name="stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3>
*
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
* </code></pre>
*
* Read more about <code>doThrow()</code>|<code>doAnswer()</code> family of methods in <a href="#12">section 12</a>.
* <p>
*
* <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification" name="in_order_verification">Verification in order</a></h3>
*
* <pre class="code"><code class="java">
* // A. Single mock whose methods must be invoked in a particular order
* List singleMock = mock(List.class);
*
* //using a single mock
* singleMock.add("was added first");
* singleMock.add("was added second");
*
* //create an inOrder verifier for a single mock
* InOrder inOrder = inOrder(singleMock);
*
* //following will make sure that add is first called with "was added first", then with "was added second"
* inOrder.verify(singleMock).add("was added first");
* inOrder.verify(singleMock).add("was added second");
*
* // B. Multiple mocks that must be used in a particular order
* List firstMock = mock(List.class);
* List secondMock = mock(List.class);
*
* //using mocks
* firstMock.add("was called first");
* secondMock.add("was called second");
*
* //create inOrder object passing any mocks that need to be verified in order
* InOrder inOrder = inOrder(firstMock, secondMock);
*
* //following will make sure that firstMock was called before secondMock
* inOrder.verify(firstMock).add("was called first");
* inOrder.verify(secondMock).add("was called second");
*
* // Oh, and A + B can be mixed together at will
* </code></pre>
*
* Verification in order is flexible - <b>you don't have to verify all
* interactions</b> one-by-one but only those that you are interested in
* testing in order.
* <p>
* Also, you can create an InOrder object passing only the mocks that are relevant for
* in-order verification.
*
*
*
*
* <h3 id="7">7. <a class="meaningful_link" href="#never_verification" name="never_verification">Making sure interaction(s) never happened on mock</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks - only mockOne is interacted
* mockOne.add("one");
*
* //ordinary verification
* verify(mockOne).add("one");
*
* //verify that method was never called on a mock
* verify(mockOne, never()).add("two");
*
* </code></pre>
*
*
*
*
* <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations" name="finding_redundant_invocations">Finding redundant invocations</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks
* mockedList.add("one");
* mockedList.add("two");
*
* verify(mockedList).add("one");
*
* //following verification will fail
* verifyNoMoreInteractions(mockedList);
* </code></pre>
*
* A word of <b>warning</b>:
* 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.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
* Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests.
*
* <p>
* See also {@link Mockito#never()} - it is more explicit and
* communicates the intent well.
* <p>
*
*
*
*
* <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation" name="mock_annotation">Shorthand for mocks creation - <code>@Mock</code> annotation</a></h3>
*
* <ul>
* <li>Minimizes repetitive mock creation code.</li>
* <li>Makes the test class more readable.</li>
* <li>Makes the verification error easier to read because the <b>field name</b>
* is used to identify the mock.</li>
* </ul>
*
* <pre class="code"><code class="java">
* public class ArticleManagerTest {
*
* @Mock private ArticleCalculator calculator;
* @Mock private ArticleDatabase database;
* @Mock private UserProvider userProvider;
*
* private ArticleManager manager;
*
* @org.junit.jupiter.api.Test
* void testSomethingInJunit5(@Mock ArticleDatabase database) {
* </code></pre>
*
* <b>Important!</b> This needs to be somewhere in the base class or a test
* runner:
*
* <pre class="code"><code class="java">
* MockitoAnnotations.openMocks(testClass);
* </code></pre>
*
* You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}.
* For JUnit5 tests, refer to the JUnit5 extension described in <a href="#45">section 45</a>.
* <p>
* Read more here: {@link MockitoAnnotations}
*
*
*
*
* <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls" name="stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3>
*
* Sometimes we need to stub with different return value/exception for the same
* method call. Typical use case could be mocking iterators.
* Original version of Mockito did not have this feature to promote simple mocking.
* For example, instead of iterators one could use {@link Iterable} or simply
* collections. Those offer natural ways of stubbing (e.g. using real
* collections). In rare scenarios stubbing consecutive calls could be useful,
* though:
* <p>
*
* <pre class="code"><code class="java">
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException())
* .thenReturn("foo");
*
* //First call: throws runtime exception:
* mock.someMethod("some arg");
*
* //Second call: prints "foo"
* System.out.println(mock.someMethod("some arg"));
*
* //Any consecutive call: prints "foo" as well (last stubbing wins).
* System.out.println(mock.someMethod("some arg"));
* </code></pre>
*
* Alternative, shorter version of consecutive stubbing:
*
* <pre class="code"><code class="java">
* when(mock.someMethod("some arg"))
* .thenReturn("one", "two", "three");
* </code></pre>
*
* <strong>Warning</strong> : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with the same matchers or arguments
* is used, then each stubbing will override the previous one:
*
* <pre class="code"><code class="java">
* //All mock.someMethod("some arg") calls will return "two"
* when(mock.someMethod("some arg"))
* .thenReturn("one")
* when(mock.someMethod("some arg"))
* .thenReturn("two")
* </code></pre>
*
*
*
* <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs" name="answer_stubs">Stubbing with callbacks</a></h3>
*
* Allows stubbing with generic {@link Answer} interface.
* <p>
* Yet another controversial feature which was not included in Mockito
* originally. We recommend simply stubbing with <code>thenReturn()</code> or
* <code>thenThrow()</code>, which should be enough to test/test-drive
* any clean & simple code. However, if you do have a need to stub with the generic Answer interface, here is an example:
*
* <pre class="code"><code class="java">
* when(mock.someMethod(anyString())).thenAnswer(
* new Answer() {
* public Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Object mock = invocation.getMock();
* return "called with arguments: " + Arrays.toString(args);
* }
* });
*
* //Following prints "called with arguments: [foo]"
* System.out.println(mock.someMethod("foo"));
* </code></pre>
*
*
*
*
* <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs" name="do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>|
* <code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a></h3>
*
* Stubbing void methods requires a different approach from {@link Mockito#when(Object)} because the compiler does not
* like void methods inside brackets...
* <p>
* Use <code>doThrow()</code> when you want to stub a void method with an exception:
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
* </code></pre>
* </p>
*
* <p>
* You can use <code>doThrow()</code>, <code>doAnswer()</code>, <code>doNothing()</code>, <code>doReturn()</code>
* and <code>doCallRealMethod()</code> in place of the corresponding call with <code>when()</code>, for any method.
* It is necessary when you
* <ul>
* <li>stub void methods</li>
* <li>stub methods on spy objects (see below)</li>
* <li>stub the same method more than once, to change the behaviour of a mock in the middle of a test.</li>
* </ul>
* but you may prefer to use these methods in place of the alternative with <code>when()</code>, for all of your stubbing calls.
* <p>
* Read more about these methods:
* <p>
* {@link Mockito#doReturn(Object)}
* <p>
* {@link Mockito#doThrow(Throwable...)}
* <p>
* {@link Mockito#doThrow(Class)}
* <p>
* {@link Mockito#doAnswer(Answer)}
* <p>
* {@link Mockito#doNothing()}
* <p>
* {@link Mockito#doCallRealMethod()}
*
*
*
*
* <h3 id="13">13. <a class="meaningful_link" href="#spy" name="spy">Spying on real objects</a></h3>
*
* You can create spies of real objects. When you use the spy then the <b>real</b> methods are called
* (unless a method was stubbed).
* <p>
* Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
*
* <p>
* Spying on real objects can be associated with "partial mocking" concept.
* <b>Before the release 1.8</b>, Mockito spies were not real partial mocks.
* The reason was we thought partial mock is a code smell.
* At some point we found legitimate use cases for partial mocks
* (3rd party interfaces, interim refactoring of legacy code).
* <p>
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //optionally, you can stub out some methods:
* when(spy.size()).thenReturn(100);
*
* //using the spy calls <b>*real*</b> methods
* spy.add("one");
* spy.add("two");
*
* //prints "one" - the first element of a list
* System.out.println(spy.get(0));
*
* //size() method was stubbed - 100 is printed
* System.out.println(spy.size());
*
* //optionally, you can verify
* verify(spy).add("one");
* verify(spy).add("two");
* </code></pre>
*
* <h4>Important gotcha on spying real objects!</h4>
* <ol>
* <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
* Therefore when using spies please consider <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code> family of
* methods for stubbing. Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
* So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
* and their effect on real instance state.
* 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>,
* you won't see any effects on the real instance.
* </li>
*
* <li>Watch out for final methods.
* 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.
* Also you won't be able to verify those method as well.
* </li>
* </ol>
*
*
*
*
* <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn" name="defaultreturn">default return values of unstubbed invocations</a> (Since 1.7)</h3>
*
* You can create a mock with specified strategy for its return values.
* It's quite an advanced feature and typically you don't need it to write decent tests.
* However, it can be helpful for working with <b>legacy systems</b>.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* <p>
* Read more about this interesting implementation of <i>Answer</i>: {@link Mockito#RETURNS_SMART_NULLS}
*
*
*
*
* <h3 id="15">15. <a class="meaningful_link" href="#captors" name="captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* This is also the recommended way of matching arguments because it makes tests clean & simple.
* In some situations though, it is helpful to assert on certain arguments after the actual verification.
* For example:
* <pre class="code"><code class="java">
* ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
* verify(mock).doSomething(argument.capture());
* assertEquals("John", argument.getValue().getName());
* </code></pre>
*
* <b>Warning:</b> it is recommended to use ArgumentCaptor with verification <b>but not</b> with stubbing.
* Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block.
* Also it may reduce defect localization because if stubbed method was not called then no argument is captured.
* <p>
* In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class).
* Both techniques can be used for making sure certain arguments were passed to mocks.
* However, ArgumentCaptor may be a better fit if:
* <ul>
* <li>custom argument matcher is not likely to be reused</li>
* <li>you just need it to assert on argument values to complete verification</li>
* </ul>
* Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
*
*
*
*
* <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks" name="partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3>
*
* Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito.
* Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
* <p>
* <b>Before release 1.8</b> <code>spy()</code> was not producing real partial mocks and it was confusing for some users.
* Read more about spying: <a href="#13">here</a> or in javadoc for {@link Mockito#spy(Object)} method.
* <p>
* <pre class="code"><code class="java">
* //you can create partial mock with spy() method:
* List list = spy(new LinkedList());
*
* //you can enable partial mock capabilities selectively on mocks:
* Foo mock = mock(Foo.class);
* //Be sure the real implementation is 'safe'.
* //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
* when(mock.someMethod()).thenCallRealMethod();
* </code></pre>
*
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
*
*
*
*
* <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks" name="resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3>
*
* Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
* Normally, you don't need to reset your mocks, just create new mocks for each test method.
* <p>
* Instead of <code>reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
* <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.
* Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
* There are several threads about it on mockito mailing list.
* <p>
* The only reason we added <code>reset()</code> method is to
* make it possible to work with container-injected mocks.
* For more information see FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
* <p>
* <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).
* <pre class="code"><code class="java">
* List mock = mock(List.class);
* when(mock.size()).thenReturn(10);
* mock.add(1);
*
* reset(mock);
* //at this point the mock forgot any interactions & stubbing
* </code></pre>
*
*
*
*
* <h3 id="18">18. <a class="meaningful_link" href="#framework_validation" name="framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3>
*
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ:
* <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
* <p>
* In case of questions you may also post to mockito mailing list:
* <a href="https://groups.google.com/group/mockito">https://groups.google.com/group/mockito</a>
* <p>
* Next, you should know that Mockito validates if you use it correctly <b>all the time</b>.
* However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()}
*
*
*
*
* <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito" name="bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3>
*
* Behavior Driven Development style of writing tests uses <b>//given //when //then</b> comments as fundamental parts of your test methods.
* This is exactly how we write our tests and we warmly encourage you to do so!
* <p>
* Start learning about BDD here: <a href="https://en.wikipedia.org/wiki/Behavior-driven_development">https://en.wikipedia.org/wiki/Behavior-driven_development</a>
* <p>
* 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.
* It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test.
* Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method.
* Now it really nicely integrates with the <b>given</b> component of a BDD style test!
* <p>
* Here is how the test might look like:
* <pre class="code"><code class="java">
* import static org.mockito.BDDMockito.*;
*
* Seller seller = mock(Seller.class);
* Shop shop = new Shop(seller);
*
* public void shouldBuyBread() throws Exception {
* //given
* given(seller.askForBread()).willReturn(new Bread());
*
* //when
* Goods goods = shop.buyBread();
*
* //then
* assertThat(goods, containBread());
* }
* </code></pre>
*
*
*
*
* <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks" name="serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3>
*
* Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
* <p>
* WARNING: This should be rarely used in unit testing.
* <p>
* The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
* was in a web environment and the objects from the external dependency were being serialized to pass between layers.
* <p>
* To create serializable mock use {@link MockSettings#serializable()}:
* <pre class="code"><code class="java">
* List serializableMock = mock(List.class, withSettings().serializable());
* </code></pre>
* <p>
* The mock can be serialized assuming all the normal <a href='https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html'>
* serialization requirements</a> are met by the class.
* <p>
* Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version
* which accepts MockSettings. No worries, you will hardly ever use it.
*
* <pre class="code"><code class="java">
* List<Object> list = new ArrayList<Object>();
* List<Object> spy = mock(ArrayList.class, withSettings()
* .spiedInstance(list)
* .defaultAnswer(CALLS_REAL_METHODS)
* .serializable());
* </code></pre>
*
*
*
*
* <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation" name="captor_annotation"><code>@Captor</code></a>,
* <a class="meaningful_link" href="#spy_annotation" name="spy_annotation"><code>@Spy</code></a>,
* <a class="meaningful_link" href="#injectmocks_annotation" name="injectmocks_annotation"><code>@InjectMocks</code></a> (Since 1.8.3)</h3>
*
* <p>
* Release 1.8.3 brings new annotations that may be helpful on occasion:
*
* <ul>
* <li>@{@link Captor} simplifies creation of {@link ArgumentCaptor}
* - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings
* <li>@{@link Spy} - you can use it instead {@link Mockito#spy(Object)}.
* <li>@{@link InjectMocks} - injects mock or spy fields into tested object automatically.
* </ul>
*
* <p>
* Note that @{@link InjectMocks} can also be used in combination with the @{@link Spy} annotation, it means
* that Mockito will inject mocks into the partial mock under test. This complexity is another good reason why you
* should only use partial mocks as a last resort. See point 16 about partial mocks.
*
* <p>
* All new annotations are <b>*only*</b> processed on {@link MockitoAnnotations#openMocks(Object)}.
* Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule:
* {@link MockitoRule}.
* <p>
*
*
*
*
* <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout" name="verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3>
* <p>
* Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired
* interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent
* conditions.
* <p>
* This feature should be used rarely - figure out a better way of testing your multi-threaded system.
* <p>
* Not yet implemented to work with InOrder verification.
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
* //passes when someMethod() is called no later than within 100 ms
* //exits immediately when verification is satisfied (e.g. may not wait full 100 ms)
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes as soon as someMethod() has been called 2 times under 100 ms
* verify(mock, timeout(100).times(2)).someMethod();
*
* //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms
* verify(mock, timeout(100).atLeast(2)).someMethod();
* </code></pre>
*
*
*
*
* <h3 id="23">23. <a class="meaningful_link" href="#automatic_instantiation" name="automatic_instantiation">Automatic instantiation of <code>@Spies</code>,
* <code>@InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection" name="constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3>
*
* <p>
* Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields
* using <b>constructor</b> injection, <b>setter</b> injection, or <b>field</b> injection.
* <p>
* To take advantage of this feature you need to use {@link MockitoAnnotations#openMocks(Object)}, {@link MockitoJUnitRunner}
* or {@link MockitoRule}.
* <p>
* Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks}
* <pre class="code"><code class="java">
* //instead:
* @Spy BeerDrinker drinker = new BeerDrinker();
* //you can write:
* @Spy BeerDrinker drinker;
*
* //same applies to @InjectMocks annotation:
* @InjectMocks LocalPub;
* </code></pre>
*
*
*
*
* <h3 id="24">24. <a class="meaningful_link" href="#one_liner_stub" name="one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow you to create mocks when stubbing.
* Basically, it allows to create a stub in one line of code.
* This can be helpful to keep test code clean.
* For example, some boring stub can be created & stubbed at field initialization in a test:
* <pre class="code"><code class="java">
* public class CarTest {
* Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
*
* @Test public void should... {}
* </code></pre>
*
*
*
*
* <h3 id="25">25. <a class="meaningful_link" href="#ignore_stubs_verification" name="ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow to ignore stubbing for the sake of verification.
* Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...));
* Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>Some examples:
* <pre class="code"><code class="java">
* verify(mock).foo();
* verify(mockTwo).bar();
*
* //ignores all stubbed methods:
* verifyNoMoreInteractions(ignoreStubs(mock, mockTwo));
*
* //creates InOrder that will ignore stubbed
* InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));
* inOrder.verify(mock).foo();
* inOrder.verify(mockTwo).bar();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
* <p>
* Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)}
*
*
*
*
* <h3 id="26">26. <a class="meaningful_link" href="#mocking_details" name="mocking_details">Mocking details</a> (Improved in 2.2.x)</h3>
* <p>
*
* Mockito offers API to inspect the details of a mock object.
* This API is useful for advanced users and mocking framework integrators.
*
* <pre class="code"><code class="java">
* //To identify whether a particular object is a mock or a spy:
* Mockito.mockingDetails(someObject).isMock();
* Mockito.mockingDetails(someObject).isSpy();
*
* //Getting details like type to mock or default answer:
* MockingDetails details = mockingDetails(mock);
* details.getMockCreationSettings().getTypeToMock();
* details.getMockCreationSettings().getDefaultAnswer();
*
* //Getting invocations and stubbings of the mock:
* MockingDetails details = mockingDetails(mock);
* details.getInvocations();
* details.getStubbings();
*
* //Printing all interactions (including stubbing, unused stubs)
* System.out.println(mockingDetails(mock).printInvocations());
* </code></pre>
*
* For more information see javadoc for {@link MockingDetails}.
*
* <h3 id="27">27. <a class="meaningful_link" href="#delegating_call_to_real_instance" name="delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3>
*
* <p>Useful for spies or partial mocks of objects <strong>that are difficult to mock or spy</strong> using the usual spy API.
* Since Mockito 1.10.11, the delegate may or may not be of the same type as the mock.