• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito.internal.exceptions;
6 
7 import static org.mockito.internal.reporting.Pluralizer.pluralize;
8 import static org.mockito.internal.reporting.Pluralizer.were_exactly_x_interactions;
9 import static org.mockito.internal.util.StringUtil.join;
10 
11 import java.lang.reflect.Field;
12 import java.lang.reflect.Method;
13 import java.util.*;
14 import org.mockito.exceptions.base.MockitoAssertionError;
15 import org.mockito.exceptions.base.MockitoException;
16 import org.mockito.exceptions.base.MockitoInitializationException;
17 import org.mockito.exceptions.misusing.*;
18 import org.mockito.exceptions.verification.MoreThanAllowedActualInvocations;
19 import org.mockito.exceptions.verification.NeverWantedButInvoked;
20 import org.mockito.exceptions.verification.NoInteractionsWanted;
21 import org.mockito.exceptions.verification.SmartNullPointerException;
22 import org.mockito.exceptions.verification.TooFewActualInvocations;
23 import org.mockito.exceptions.verification.TooManyActualInvocations;
24 import org.mockito.exceptions.verification.VerificationInOrderFailure;
25 import org.mockito.exceptions.verification.WantedButNotInvoked;
26 import org.mockito.internal.debugging.LocationImpl;
27 import org.mockito.internal.exceptions.util.ScenarioPrinter;
28 import org.mockito.internal.junit.ExceptionFactory;
29 import org.mockito.internal.matchers.LocalizedMatcher;
30 import org.mockito.internal.util.MockUtil;
31 import org.mockito.invocation.DescribedInvocation;
32 import org.mockito.invocation.Invocation;
33 import org.mockito.invocation.InvocationOnMock;
34 import org.mockito.invocation.Location;
35 import org.mockito.listeners.InvocationListener;
36 import org.mockito.mock.SerializableMode;
37 
38 /**
39  * Reports verification and misusing errors.
40  * <p>
41  * One of the key points of mocking library is proper verification/exception
42  * messages. All messages in one place makes it easier to tune and amend them.
43  * <p>
44  * Reporter can be injected and therefore is easily testable.
45  * <p>
46  * Generally, exception messages are full of line breaks to make them easy to
47  * read (xunit plugins take only fraction of screen on modern IDEs).
48  */
49 public class Reporter {
50 
51     private static final String NON_PUBLIC_PARENT =
52             "Mocking methods declared on non-public parent classes is not supported.";
53 
Reporter()54     private Reporter() {}
55 
checkedExceptionInvalid(Throwable t)56     public static MockitoException checkedExceptionInvalid(Throwable t) {
57         return new MockitoException(
58                 join("Checked exception is invalid for this method!", "Invalid: " + t));
59     }
60 
cannotStubWithNullThrowable()61     public static MockitoException cannotStubWithNullThrowable() {
62         return new MockitoException(join("Cannot stub with null throwable!"));
63     }
64 
unfinishedStubbing(Location location)65     public static MockitoException unfinishedStubbing(Location location) {
66         return new UnfinishedStubbingException(
67                 join(
68                         "Unfinished stubbing detected here:",
69                         location,
70                         "",
71                         "E.g. thenReturn() may be missing.",
72                         "Examples of correct stubbing:",
73                         "    when(mock.isOk()).thenReturn(true);",
74                         "    when(mock.isOk()).thenThrow(exception);",
75                         "    doThrow(exception).when(mock).someVoidMethod();",
76                         "Hints:",
77                         " 1. missing thenReturn()",
78                         " 2. you are trying to stub a final method, which is not supported",
79                         " 3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed",
80                         ""));
81     }
82 
incorrectUseOfApi()83     public static MockitoException incorrectUseOfApi() {
84         return new MockitoException(
85                 join(
86                         "Incorrect use of API detected here:",
87                         new LocationImpl(),
88                         "",
89                         "You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.",
90                         "Examples of correct usage:",
91                         "    when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);",
92                         "    when(mock.isOk()).thenReturn(true, false).thenThrow(exception);",
93                         ""));
94     }
95 
missingMethodInvocation()96     public static MockitoException missingMethodInvocation() {
97         return new MissingMethodInvocationException(
98                 join(
99                         "when() requires an argument which has to be 'a method call on a mock'.",
100                         "For example:",
101                         "    when(mock.getArticles()).thenReturn(articles);",
102                         "",
103                         "Also, this error might show up because:",
104                         "1. you stub either of: final/private/equals()/hashCode() methods.",
105                         "   Those methods *cannot* be stubbed/verified.",
106                         "   " + NON_PUBLIC_PARENT,
107                         "2. inside when() you don't call method on mock but on some other object.",
108                         ""));
109     }
110 
unfinishedVerificationException(Location location)111     public static MockitoException unfinishedVerificationException(Location location) {
112         return new UnfinishedVerificationException(
113                 join(
114                         "Missing method call for verify(mock) here:",
115                         location,
116                         "",
117                         "Example of correct verification:",
118                         "    verify(mock).doSomething()",
119                         "",
120                         "Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.",
121                         "Those methods *cannot* be stubbed/verified.",
122                         NON_PUBLIC_PARENT,
123                         ""));
124     }
125 
notAMockPassedToVerify(Class<?> type)126     public static MockitoException notAMockPassedToVerify(Class<?> type) {
127         return new NotAMockException(
128                 join(
129                         "Argument passed to verify() is of type "
130                                 + type.getSimpleName()
131                                 + " and is not a mock!",
132                         "Make sure you place the parenthesis correctly!",
133                         "See the examples of correct verifications:",
134                         "    verify(mock).someMethod();",
135                         "    verify(mock, times(10)).someMethod();",
136                         "    verify(mock, atLeastOnce()).someMethod();"));
137     }
138 
nullPassedToVerify()139     public static MockitoException nullPassedToVerify() {
140         return new NullInsteadOfMockException(
141                 join(
142                         "Argument passed to verify() should be a mock but is null!",
143                         "Examples of correct verifications:",
144                         "    verify(mock).someMethod();",
145                         "    verify(mock, times(10)).someMethod();",
146                         "    verify(mock, atLeastOnce()).someMethod();",
147                         "    not: verify(mock.someMethod());",
148                         "Also, if you use @Mock annotation don't miss openMocks()"));
149     }
150 
notAMockPassedToWhenMethod()151     public static MockitoException notAMockPassedToWhenMethod() {
152         return new NotAMockException(
153                 join(
154                         "Argument passed to when() is not a mock!",
155                         "Example of correct stubbing:",
156                         "    doThrow(new RuntimeException()).when(mock).someMethod();"));
157     }
158 
nullPassedToWhenMethod()159     public static MockitoException nullPassedToWhenMethod() {
160         return new NullInsteadOfMockException(
161                 join(
162                         "Argument passed to when() is null!",
163                         "Example of correct stubbing:",
164                         "    doThrow(new RuntimeException()).when(mock).someMethod();",
165                         "Also, if you use @Mock annotation don't miss openMocks()"));
166     }
167 
mocksHaveToBePassedToVerifyNoMoreInteractions()168     public static MockitoException mocksHaveToBePassedToVerifyNoMoreInteractions() {
169         return new MockitoException(
170                 join(
171                         "Method requires argument(s)!",
172                         "Pass mocks that should be verified, e.g:",
173                         "    verifyNoMoreInteractions(mockOne, mockTwo);",
174                         "    verifyNoInteractions(mockOne, mockTwo);",
175                         ""));
176     }
177 
notAMockPassedToVerifyNoMoreInteractions()178     public static MockitoException notAMockPassedToVerifyNoMoreInteractions() {
179         return new NotAMockException(
180                 join(
181                         "Argument(s) passed is not a mock!",
182                         "Examples of correct verifications:",
183                         "    verifyNoMoreInteractions(mockOne, mockTwo);",
184                         "    verifyNoInteractions(mockOne, mockTwo);",
185                         ""));
186     }
187 
nullPassedToVerifyNoMoreInteractions()188     public static MockitoException nullPassedToVerifyNoMoreInteractions() {
189         return new NullInsteadOfMockException(
190                 join(
191                         "Argument(s) passed is null!",
192                         "Examples of correct verifications:",
193                         "    verifyNoMoreInteractions(mockOne, mockTwo);",
194                         "    verifyNoInteractions(mockOne, mockTwo);"));
195     }
196 
notAMockPassedWhenCreatingInOrder()197     public static MockitoException notAMockPassedWhenCreatingInOrder() {
198         return new NotAMockException(
199                 join(
200                         "Argument(s) passed is not a mock!",
201                         "Pass mocks that require verification in order.",
202                         "For example:",
203                         "    InOrder inOrder = inOrder(mockOne, mockTwo);"));
204     }
205 
nullPassedWhenCreatingInOrder()206     public static MockitoException nullPassedWhenCreatingInOrder() {
207         return new NullInsteadOfMockException(
208                 join(
209                         "Argument(s) passed is null!",
210                         "Pass mocks that require verification in order.",
211                         "For example:",
212                         "    InOrder inOrder = inOrder(mockOne, mockTwo);"));
213     }
214 
mocksHaveToBePassedWhenCreatingInOrder()215     public static MockitoException mocksHaveToBePassedWhenCreatingInOrder() {
216         return new MockitoException(
217                 join(
218                         "Method requires argument(s)!",
219                         "Pass mocks that require verification in order.",
220                         "For example:",
221                         "    InOrder inOrder = inOrder(mockOne, mockTwo);"));
222     }
223 
inOrderRequiresFamiliarMock()224     public static MockitoException inOrderRequiresFamiliarMock() {
225         return new MockitoException(
226                 join(
227                         "InOrder can only verify mocks that were passed in during creation of InOrder.",
228                         "For example:",
229                         "    InOrder inOrder = inOrder(mockOne);",
230                         "    inOrder.verify(mockOne).doStuff();"));
231     }
232 
invalidUseOfMatchers( int expectedMatchersCount, List<LocalizedMatcher> recordedMatchers)233     public static MockitoException invalidUseOfMatchers(
234             int expectedMatchersCount, List<LocalizedMatcher> recordedMatchers) {
235         return new InvalidUseOfMatchersException(
236                 join(
237                         "Invalid use of argument matchers!",
238                         expectedMatchersCount
239                                 + " matchers expected, "
240                                 + recordedMatchers.size()
241                                 + " recorded:"
242                                 + locationsOf(recordedMatchers),
243                         "",
244                         "This exception may occur if matchers are combined with raw values:",
245                         "    //incorrect:",
246                         "    someMethod(any(), \"raw String\");",
247                         "When using matchers, all arguments have to be provided by matchers.",
248                         "For example:",
249                         "    //correct:",
250                         "    someMethod(any(), eq(\"String by matcher\"));",
251                         "",
252                         "For more info see javadoc for Matchers class.",
253                         ""));
254     }
255 
incorrectUseOfAdditionalMatchers( String additionalMatcherName, int expectedSubMatchersCount, Collection<LocalizedMatcher> matcherStack)256     public static MockitoException incorrectUseOfAdditionalMatchers(
257             String additionalMatcherName,
258             int expectedSubMatchersCount,
259             Collection<LocalizedMatcher> matcherStack) {
260         return new InvalidUseOfMatchersException(
261                 join(
262                         "Invalid use of argument matchers inside additional matcher "
263                                 + additionalMatcherName
264                                 + " !",
265                         new LocationImpl(),
266                         "",
267                         expectedSubMatchersCount
268                                 + " sub matchers expected, "
269                                 + matcherStack.size()
270                                 + " recorded:",
271                         locationsOf(matcherStack),
272                         "",
273                         "This exception may occur if matchers are combined with raw values:",
274                         "    //incorrect:",
275                         "    someMethod(AdditionalMatchers.and(isNotNull(), \"raw String\");",
276                         "When using matchers, all arguments have to be provided by matchers.",
277                         "For example:",
278                         "    //correct:",
279                         "    someMethod(AdditionalMatchers.and(isNotNull(), eq(\"raw String\"));",
280                         "",
281                         "For more info see javadoc for Matchers and AdditionalMatchers classes.",
282                         ""));
283     }
284 
stubPassedToVerify(Object mock)285     public static MockitoException stubPassedToVerify(Object mock) {
286         return new CannotVerifyStubOnlyMock(
287                 join(
288                         "Argument \""
289                                 + MockUtil.getMockName(mock)
290                                 + "\" passed to verify is a stubOnly() mock which cannot be verified.",
291                         "If you intend to verify invocations on this mock, don't use stubOnly() in its MockSettings."));
292     }
293 
reportNoSubMatchersFound(String additionalMatcherName)294     public static MockitoException reportNoSubMatchersFound(String additionalMatcherName) {
295         return new InvalidUseOfMatchersException(
296                 join(
297                         "No matchers found for additional matcher " + additionalMatcherName,
298                         new LocationImpl(),
299                         ""));
300     }
301 
locationsOf(Collection<LocalizedMatcher> matchers)302     private static Object locationsOf(Collection<LocalizedMatcher> matchers) {
303         List<String> description = new ArrayList<>();
304         for (LocalizedMatcher matcher : matchers) {
305             description.add(matcher.getLocation().toString());
306         }
307         return join(description.toArray());
308     }
309 
argumentsAreDifferent( String wanted, List<String> actualCalls, List<Location> actualLocations)310     public static AssertionError argumentsAreDifferent(
311             String wanted, List<String> actualCalls, List<Location> actualLocations) {
312         if (actualCalls == null
313                 || actualLocations == null
314                 || actualCalls.size() != actualLocations.size()) {
315             throw new IllegalArgumentException("actualCalls and actualLocations list must match");
316         }
317 
318         StringBuilder actualBuilder = new StringBuilder();
319         StringBuilder messageBuilder = new StringBuilder();
320         messageBuilder
321                 .append("\n")
322                 .append("Argument(s) are different! Wanted:\n")
323                 .append(wanted)
324                 .append("\n")
325                 .append(new LocationImpl())
326                 .append("\n")
327                 .append("Actual invocations have different arguments:\n");
328 
329         for (int i = 0; i < actualCalls.size(); i++) {
330             actualBuilder.append(actualCalls.get(i)).append("\n");
331 
332             messageBuilder
333                     .append(actualCalls.get(i))
334                     .append("\n")
335                     .append(actualLocations.get(i))
336                     .append("\n");
337         }
338 
339         return ExceptionFactory.createArgumentsAreDifferentException(
340                 messageBuilder.toString(), wanted, actualBuilder.toString());
341     }
342 
wantedButNotInvoked(DescribedInvocation wanted)343     public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted) {
344         return new WantedButNotInvoked(createWantedButNotInvokedMessage(wanted));
345     }
346 
wantedButNotInvoked( DescribedInvocation wanted, List<? extends DescribedInvocation> invocations)347     public static MockitoAssertionError wantedButNotInvoked(
348             DescribedInvocation wanted, List<? extends DescribedInvocation> invocations) {
349         String allInvocations;
350         if (invocations.isEmpty()) {
351             allInvocations = "Actually, there were zero interactions with this mock.\n";
352         } else {
353             StringBuilder sb =
354                     new StringBuilder("\nHowever, there ")
355                             .append(were_exactly_x_interactions(invocations.size()))
356                             .append(" with this mock:\n");
357             for (DescribedInvocation i : invocations) {
358                 sb.append(i).append("\n").append(i.getLocation()).append("\n\n");
359             }
360             allInvocations = sb.toString();
361         }
362 
363         String message = createWantedButNotInvokedMessage(wanted);
364         return new WantedButNotInvoked(message + allInvocations);
365     }
366 
createWantedButNotInvokedMessage(DescribedInvocation wanted)367     private static String createWantedButNotInvokedMessage(DescribedInvocation wanted) {
368         return join("Wanted but not invoked:", wanted.toString(), new LocationImpl(), "");
369     }
370 
wantedButNotInvokedInOrder( DescribedInvocation wanted, DescribedInvocation previous)371     public static MockitoAssertionError wantedButNotInvokedInOrder(
372             DescribedInvocation wanted, DescribedInvocation previous) {
373         return new VerificationInOrderFailure(
374                 join(
375                         "Verification in order failure",
376                         "Wanted but not invoked:",
377                         wanted.toString(),
378                         new LocationImpl(),
379                         "Wanted anywhere AFTER following interaction:",
380                         previous.toString(),
381                         previous.getLocation(),
382                         ""));
383     }
384 
tooManyActualInvocations( int wantedCount, int actualCount, DescribedInvocation wanted, List<Location> locations)385     public static MockitoAssertionError tooManyActualInvocations(
386             int wantedCount,
387             int actualCount,
388             DescribedInvocation wanted,
389             List<Location> locations) {
390         String message =
391                 createTooManyInvocationsMessage(wantedCount, actualCount, wanted, locations);
392         return new TooManyActualInvocations(message);
393     }
394 
createTooManyInvocationsMessage( int wantedCount, int actualCount, DescribedInvocation wanted, List<Location> invocations)395     private static String createTooManyInvocationsMessage(
396             int wantedCount,
397             int actualCount,
398             DescribedInvocation wanted,
399             List<Location> invocations) {
400         return join(
401                 wanted.toString(),
402                 "Wanted " + pluralize(wantedCount) + ":",
403                 new LocationImpl(),
404                 "But was " + pluralize(actualCount) + ":",
405                 createAllLocationsMessage(invocations),
406                 "");
407     }
408 
neverWantedButInvoked( DescribedInvocation wanted, List<Invocation> invocations)409     public static MockitoAssertionError neverWantedButInvoked(
410             DescribedInvocation wanted, List<Invocation> invocations) {
411 
412         return new NeverWantedButInvoked(
413                 join(
414                         wanted.toString(),
415                         "Never wanted here:",
416                         new LocationImpl(),
417                         "But invoked here:",
418                         createAllLocationsArgsMessage(invocations)));
419     }
420 
tooManyActualInvocationsInOrder( int wantedCount, int actualCount, DescribedInvocation wanted, List<Location> invocations)421     public static MockitoAssertionError tooManyActualInvocationsInOrder(
422             int wantedCount,
423             int actualCount,
424             DescribedInvocation wanted,
425             List<Location> invocations) {
426         String message =
427                 createTooManyInvocationsMessage(wantedCount, actualCount, wanted, invocations);
428         return new VerificationInOrderFailure(join("Verification in order failure:" + message));
429     }
430 
createAllLocationsMessage(List<Location> locations)431     private static String createAllLocationsMessage(List<Location> locations) {
432         if (locations == null) {
433             return "\n";
434         }
435         StringBuilder sb = new StringBuilder();
436         for (Location location : locations) {
437             sb.append(location).append("\n");
438         }
439         return sb.toString();
440     }
441 
createAllLocationsArgsMessage(List<Invocation> invocations)442     private static String createAllLocationsArgsMessage(List<Invocation> invocations) {
443         StringBuilder sb = new StringBuilder();
444         for (Invocation invocation : invocations) {
445             Location location = invocation.getLocation();
446             if (location == null) {
447                 continue;
448             }
449             sb.append(location)
450                     .append(" with arguments: ")
451                     .append(Arrays.toString(invocation.getArguments()))
452                     .append("\n");
453         }
454         return sb.toString();
455     }
456 
createTooFewInvocationsMessage( org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> locations)457     private static String createTooFewInvocationsMessage(
458             org.mockito.internal.reporting.Discrepancy discrepancy,
459             DescribedInvocation wanted,
460             List<Location> locations) {
461         return join(
462                 wanted.toString(),
463                 "Wanted "
464                         + discrepancy.getPluralizedWantedCount()
465                         + (discrepancy.getWantedCount() == 0 ? "." : ":"),
466                 new LocationImpl(),
467                 "But was "
468                         + discrepancy.getPluralizedActualCount()
469                         + (discrepancy.getActualCount() == 0 ? "." : ":"),
470                 createAllLocationsMessage(locations));
471     }
472 
tooFewActualInvocations( org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> allLocations)473     public static MockitoAssertionError tooFewActualInvocations(
474             org.mockito.internal.reporting.Discrepancy discrepancy,
475             DescribedInvocation wanted,
476             List<Location> allLocations) {
477         String message = createTooFewInvocationsMessage(discrepancy, wanted, allLocations);
478 
479         return new TooFewActualInvocations(message);
480     }
481 
tooFewActualInvocationsInOrder( org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> locations)482     public static MockitoAssertionError tooFewActualInvocationsInOrder(
483             org.mockito.internal.reporting.Discrepancy discrepancy,
484             DescribedInvocation wanted,
485             List<Location> locations) {
486         String message = createTooFewInvocationsMessage(discrepancy, wanted, locations);
487 
488         return new VerificationInOrderFailure(join("Verification in order failure:" + message));
489     }
490 
noMoreInteractionsWanted( Invocation undesired, List<VerificationAwareInvocation> invocations)491     public static MockitoAssertionError noMoreInteractionsWanted(
492             Invocation undesired, List<VerificationAwareInvocation> invocations) {
493         ScenarioPrinter scenarioPrinter = new ScenarioPrinter();
494         String scenario = scenarioPrinter.print(invocations);
495 
496         return new NoInteractionsWanted(
497                 join(
498                         "No interactions wanted here:",
499                         new LocationImpl(),
500                         "But found this interaction on mock '"
501                                 + MockUtil.getMockName(undesired.getMock())
502                                 + "':",
503                         undesired.getLocation(),
504                         scenario));
505     }
506 
noMoreInteractionsWantedInOrder(Invocation undesired)507     public static MockitoAssertionError noMoreInteractionsWantedInOrder(Invocation undesired) {
508         return new VerificationInOrderFailure(
509                 join(
510                         "No interactions wanted here:",
511                         new LocationImpl(),
512                         "But found this interaction on mock '"
513                                 + MockUtil.getMockName(undesired.getMock())
514                                 + "':",
515                         undesired.getLocation()));
516     }
517 
noInteractionsWanted( Object mock, List<VerificationAwareInvocation> invocations)518     public static MockitoAssertionError noInteractionsWanted(
519             Object mock, List<VerificationAwareInvocation> invocations) {
520         ScenarioPrinter scenarioPrinter = new ScenarioPrinter();
521         String scenario = scenarioPrinter.print(invocations);
522 
523         List<Location> locations = new ArrayList<>();
524         for (VerificationAwareInvocation invocation : invocations) {
525             locations.add(invocation.getLocation());
526         }
527         return new NoInteractionsWanted(
528                 join(
529                         "No interactions wanted here:",
530                         new LocationImpl(),
531                         "But found these interactions on mock '"
532                                 + MockUtil.getMockName(mock)
533                                 + "':",
534                         join("", locations),
535                         scenario));
536     }
537 
cannotMockClass(Class<?> clazz, String reason)538     public static MockitoException cannotMockClass(Class<?> clazz, String reason) {
539         return new MockitoException(
540                 join(
541                         "Cannot mock/spy " + clazz,
542                         "Mockito cannot mock/spy because :",
543                         " - " + reason));
544     }
545 
cannotStubVoidMethodWithAReturnValue(String methodName)546     public static MockitoException cannotStubVoidMethodWithAReturnValue(String methodName) {
547         return new CannotStubVoidMethodWithReturnValue(
548                 join(
549                         "'"
550                                 + methodName
551                                 + "' is a *void method* and it *cannot* be stubbed with a *return value*!",
552                         "Voids are usually stubbed with Throwables:",
553                         "    doThrow(exception).when(mock).someVoidMethod();",
554                         "If you need to set the void method to do nothing you can use:",
555                         "    doNothing().when(mock).someVoidMethod();",
556                         "For more information, check out the javadocs for Mockito.doNothing().",
557                         "***",
558                         "If you're unsure why you're getting above error read on.",
559                         "Due to the nature of the syntax above problem might occur because:",
560                         "1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.",
561                         "2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/stub final methods.",
562                         "3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",
563                         "   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",
564                         "4. " + NON_PUBLIC_PARENT,
565                         ""));
566     }
567 
onlyVoidMethodsCanBeSetToDoNothing()568     public static MockitoException onlyVoidMethodsCanBeSetToDoNothing() {
569         return new MockitoException(
570                 join(
571                         "Only void methods can doNothing()!",
572                         "Example of correct use of doNothing():",
573                         "    doNothing().",
574                         "    doThrow(new RuntimeException())",
575                         "    .when(mock).someVoidMethod();",
576                         "Above means:",
577                         "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called"));
578     }
579 
wrongTypeOfReturnValue( String expectedType, String actualType, String methodName)580     public static MockitoException wrongTypeOfReturnValue(
581             String expectedType, String actualType, String methodName) {
582         return new WrongTypeOfReturnValue(
583                 join(
584                         actualType + " cannot be returned by " + methodName + "()",
585                         methodName + "() should return " + expectedType,
586                         "***",
587                         "If you're unsure why you're getting above error read on.",
588                         "Due to the nature of the syntax above problem might occur because:",
589                         "1. This exception *might* occur in wrongly written multi-threaded tests.",
590                         "   Please refer to Mockito FAQ on limitations of concurrency testing.",
591                         "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",
592                         "   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",
593                         ""));
594     }
595 
wrongTypeReturnedByDefaultAnswer( Object mock, String expectedType, String actualType, String methodName)596     public static MockitoException wrongTypeReturnedByDefaultAnswer(
597             Object mock, String expectedType, String actualType, String methodName) {
598         return new WrongTypeOfReturnValue(
599                 join(
600                         "Default answer returned a result with the wrong type:",
601                         actualType + " cannot be returned by " + methodName + "()",
602                         methodName + "() should return " + expectedType,
603                         "",
604                         "The default answer of "
605                                 + MockUtil.getMockName(mock)
606                                 + " that was configured on the mock is probably incorrectly implemented.",
607                         ""));
608     }
609 
wantedAtMostX( int maxNumberOfInvocations, int foundSize)610     public static MoreThanAllowedActualInvocations wantedAtMostX(
611             int maxNumberOfInvocations, int foundSize) {
612         return new MoreThanAllowedActualInvocations(
613                 join(
614                         "Wanted at most "
615                                 + pluralize(maxNumberOfInvocations)
616                                 + " but was "
617                                 + foundSize));
618     }
619 
misplacedArgumentMatcher(List<LocalizedMatcher> lastMatchers)620     public static MockitoException misplacedArgumentMatcher(List<LocalizedMatcher> lastMatchers) {
621         return new InvalidUseOfMatchersException(
622                 join(
623                         "Misplaced or misused argument matcher detected here:",
624                         locationsOf(lastMatchers),
625                         "",
626                         "You cannot use argument matchers outside of verification or stubbing.",
627                         "Examples of correct usage of argument matchers:",
628                         "    when(mock.get(anyInt())).thenReturn(null);",
629                         "    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());",
630                         "    verify(mock).someMethod(contains(\"foo\"))",
631                         "",
632                         "This message may appear after an NullPointerException if the last matcher is returning an object ",
633                         "like any() but the stubbed method signature expect a primitive argument, in this case,",
634                         "use primitive alternatives.",
635                         "    when(mock.get(any())); // bad use, will raise NPE",
636                         "    when(mock.get(anyInt())); // correct usage use",
637                         "",
638                         "Also, this error might show up because you use argument matchers with methods that cannot be mocked.",
639                         "Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().",
640                         NON_PUBLIC_PARENT,
641                         ""));
642     }
643 
smartNullPointerException(String invocation, Location location)644     public static MockitoException smartNullPointerException(String invocation, Location location) {
645         return new SmartNullPointerException(
646                 join(
647                         "You have a NullPointerException here:",
648                         new LocationImpl(),
649                         "because this method call was *not* stubbed correctly:",
650                         location,
651                         invocation,
652                         ""));
653     }
654 
noArgumentValueWasCaptured()655     public static MockitoException noArgumentValueWasCaptured() {
656         return new MockitoException(
657                 join(
658                         "No argument value was captured!",
659                         "You might have forgotten to use argument.capture() in verify()...",
660                         "...or you used capture() in stubbing but stubbed method was not called.",
661                         "Be aware that it is recommended to use capture() only with verify()",
662                         "",
663                         "Examples of correct argument capturing:",
664                         "    ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);",
665                         "    verify(mock).doSomething(argument.capture());",
666                         "    assertEquals(\"John\", argument.getValue().getName());",
667                         ""));
668     }
669 
extraInterfacesDoesNotAcceptNullParameters()670     public static MockitoException extraInterfacesDoesNotAcceptNullParameters() {
671         return new MockitoException(join("extraInterfaces() does not accept null parameters."));
672     }
673 
extraInterfacesAcceptsOnlyInterfaces(Class<?> wrongType)674     public static MockitoException extraInterfacesAcceptsOnlyInterfaces(Class<?> wrongType) {
675         return new MockitoException(
676                 join(
677                         "extraInterfaces() accepts only interfaces.",
678                         "You passed following type: "
679                                 + wrongType.getSimpleName()
680                                 + " which is not an interface."));
681     }
682 
extraInterfacesCannotContainMockedType(Class<?> wrongType)683     public static MockitoException extraInterfacesCannotContainMockedType(Class<?> wrongType) {
684         return new MockitoException(
685                 join(
686                         "extraInterfaces() does not accept the same type as the mocked type.",
687                         "You mocked following type: " + wrongType.getSimpleName(),
688                         "and you passed the same very interface to the extraInterfaces()"));
689     }
690 
extraInterfacesRequiresAtLeastOneInterface()691     public static MockitoException extraInterfacesRequiresAtLeastOneInterface() {
692         return new MockitoException(join("extraInterfaces() requires at least one interface."));
693     }
694 
mockedTypeIsInconsistentWithSpiedInstanceType( Class<?> mockedType, Object spiedInstance)695     public static MockitoException mockedTypeIsInconsistentWithSpiedInstanceType(
696             Class<?> mockedType, Object spiedInstance) {
697         return new MockitoException(
698                 join(
699                         "Mocked type must be the same as the type of your spied instance.",
700                         "Mocked type must be: "
701                                 + spiedInstance.getClass().getSimpleName()
702                                 + ", but is: "
703                                 + mockedType.getSimpleName(),
704                         "  //correct spying:",
705                         "  spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );",
706                         "  //incorrect - types don't match:",
707                         "  spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );"));
708     }
709 
cannotCallAbstractRealMethod()710     public static MockitoException cannotCallAbstractRealMethod() {
711         return new MockitoException(
712                 join(
713                         "Cannot call abstract real method on java object!",
714                         "Calling real methods is only possible when mocking non abstract method.",
715                         "  //correct example:",
716                         "  when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();"));
717     }
718 
cannotVerifyToString()719     public static MockitoException cannotVerifyToString() {
720         return new MockitoException(
721                 join(
722                         "Mockito cannot verify toString()",
723                         "toString() is too often used behind of scenes  (i.e. during String concatenation, in IDE debugging views). "
724                                 + "Verifying it may give inconsistent or hard to understand results. "
725                                 + "Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)",
726                         "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases."));
727     }
728 
moreThanOneAnnotationNotAllowed(String fieldName)729     public static MockitoException moreThanOneAnnotationNotAllowed(String fieldName) {
730         return new MockitoException(
731                 "You cannot have more than one Mockito annotation on a field!\n"
732                         + "The field '"
733                         + fieldName
734                         + "' has multiple Mockito annotations.\n"
735                         + "For info how to use annotations see examples in javadoc for MockitoAnnotations class.");
736     }
737 
unsupportedCombinationOfAnnotations( String undesiredAnnotationOne, String undesiredAnnotationTwo)738     public static MockitoException unsupportedCombinationOfAnnotations(
739             String undesiredAnnotationOne, String undesiredAnnotationTwo) {
740         return new MockitoException(
741                 "This combination of annotations is not permitted on a single field:\n"
742                         + "@"
743                         + undesiredAnnotationOne
744                         + " and @"
745                         + undesiredAnnotationTwo);
746     }
747 
cannotInitializeForSpyAnnotation( String fieldName, Exception details)748     public static MockitoException cannotInitializeForSpyAnnotation(
749             String fieldName, Exception details) {
750         return new MockitoException(
751                 join(
752                         "Cannot instantiate a @Spy for '" + fieldName + "' field.",
753                         "You haven't provided the instance for spying at field declaration so I tried to construct the instance.",
754                         "However, I failed because: " + details.getMessage(),
755                         "Examples of correct usage of @Spy:",
756                         "   @Spy List mock = new LinkedList();",
757                         "   @Spy Foo foo; //only if Foo has parameterless constructor",
758                         "   //also, don't forget about MockitoAnnotations.openMocks();",
759                         ""),
760                 details);
761     }
762 
cannotInitializeForInjectMocksAnnotation( String fieldName, String causeMessage)763     public static MockitoException cannotInitializeForInjectMocksAnnotation(
764             String fieldName, String causeMessage) {
765         return new MockitoException(
766                 join(
767                         "Cannot instantiate @InjectMocks field named '"
768                                 + fieldName
769                                 + "'! Cause: "
770                                 + causeMessage,
771                         "You haven't provided the instance at field declaration so I tried to construct the instance.",
772                         "Examples of correct usage of @InjectMocks:",
773                         "   @InjectMocks Service service = new Service();",
774                         "   @InjectMocks Service service;",
775                         "   //and... don't forget about some @Mocks for injection :)",
776                         ""));
777     }
778 
atMostAndNeverShouldNotBeUsedWithTimeout()779     public static MockitoException atMostAndNeverShouldNotBeUsedWithTimeout() {
780         return new FriendlyReminderException(
781                 join(
782                         "",
783                         "Don't panic! I'm just a friendly reminder!",
784                         "timeout() should not be used with atMost() or never() because...",
785                         "...it does not make much sense - the test would have passed immediately in concurrency",
786                         "We kept this method only to avoid compilation errors when upgrading Mockito.",
787                         "In future release we will remove timeout(x).atMost(y) from the API.",
788                         "If you want to find out more please refer to issue 235",
789                         ""));
790     }
791 
fieldInitialisationThrewException( Field field, Throwable details)792     public static MockitoException fieldInitialisationThrewException(
793             Field field, Throwable details) {
794         return new InjectMocksException(
795                 join(
796                         "Cannot instantiate @InjectMocks field named '"
797                                 + field.getName()
798                                 + "' of type '"
799                                 + field.getType()
800                                 + "'.",
801                         "You haven't provided the instance at field declaration so I tried to construct the instance.",
802                         "However the constructor or the initialization block threw an exception : "
803                                 + details.getMessage(),
804                         ""),
805                 details);
806     }
807 
methodDoesNotAcceptParameter(String method, String parameter)808     public static MockitoException methodDoesNotAcceptParameter(String method, String parameter) {
809         return new MockitoException(
810                 method + "() does not accept " + parameter + " See the Javadoc.");
811     }
812 
requiresAtLeastOneListener(String method)813     public static MockitoException requiresAtLeastOneListener(String method) {
814         return new MockitoException(method + "() requires at least one listener");
815     }
816 
invocationListenerThrewException( InvocationListener listener, Throwable listenerThrowable)817     public static MockitoException invocationListenerThrewException(
818             InvocationListener listener, Throwable listenerThrowable) {
819         return new MockitoException(
820                 join(
821                         "The invocation listener with type " + listener.getClass().getName(),
822                         "threw an exception : "
823                                 + listenerThrowable.getClass().getName()
824                                 + listenerThrowable.getMessage()),
825                 listenerThrowable);
826     }
827 
cannotInjectDependency( Field field, Object matchingMock, Exception details)828     public static MockitoException cannotInjectDependency(
829             Field field, Object matchingMock, Exception details) {
830         return new MockitoException(
831                 join(
832                         "Mockito couldn't inject mock dependency '"
833                                 + MockUtil.getMockName(matchingMock)
834                                 + "' on field ",
835                         "'" + field + "'",
836                         "whose type '"
837                                 + field.getDeclaringClass().getCanonicalName()
838                                 + "' was annotated by @InjectMocks in your test.",
839                         "Also I failed because: " + exceptionCauseMessageIfAvailable(details),
840                         ""),
841                 details);
842     }
843 
exceptionCauseMessageIfAvailable(Exception details)844     private static String exceptionCauseMessageIfAvailable(Exception details) {
845         if (details.getCause() == null) {
846             return details.getMessage();
847         }
848         return details.getCause().getMessage();
849     }
850 
mockedTypeIsInconsistentWithDelegatedInstanceType( Class<?> mockedType, Object delegatedInstance)851     public static MockitoException mockedTypeIsInconsistentWithDelegatedInstanceType(
852             Class<?> mockedType, Object delegatedInstance) {
853         return new MockitoException(
854                 join(
855                         "Mocked type must be the same as the type of your delegated instance.",
856                         "Mocked type must be: "
857                                 + delegatedInstance.getClass().getSimpleName()
858                                 + ", but is: "
859                                 + mockedType.getSimpleName(),
860                         "  //correct delegate:",
861                         "  spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new ArrayList()<- );",
862                         "  //incorrect - types don't match:",
863                         "  spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new HashSet()<- );"));
864     }
865 
spyAndDelegateAreMutuallyExclusive()866     public static MockitoException spyAndDelegateAreMutuallyExclusive() {
867         return new MockitoException(
868                 join(
869                         "Settings should not define a spy instance and a delegated instance at the same time."));
870     }
871 
invalidArgumentRangeAtIdentityAnswerCreationTime()872     public static MockitoException invalidArgumentRangeAtIdentityAnswerCreationTime() {
873         return new MockitoException(
874                 join(
875                         "Invalid argument index.",
876                         "The index need to be a positive number that indicates the position of the argument to return.",
877                         "However it is possible to use the -1 value to indicates that the last argument should be",
878                         "returned."));
879     }
880 
invalidArgumentPositionRangeAtInvocationTime( InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex)881     public static MockitoException invalidArgumentPositionRangeAtInvocationTime(
882             InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) {
883         return new MockitoException(
884                 join(
885                         "Invalid argument index for the current invocation of method : ",
886                         " -> "
887                                 + MockUtil.getMockName(invocation.getMock())
888                                 + "."
889                                 + invocation.getMethod().getName()
890                                 + "()",
891                         "",
892                         (willReturnLastParameter
893                                         ? "Last parameter wanted"
894                                         : "Wanted parameter at position " + argumentIndex)
895                                 + " but "
896                                 + possibleArgumentTypesOf(invocation),
897                         "The index need to be a positive number that indicates a valid position of the argument in the invocation.",
898                         "However it is possible to use the -1 value to indicates that the last argument should be returned.",
899                         ""));
900     }
901 
possibleArgumentTypesOf(InvocationOnMock invocation)902     private static StringBuilder possibleArgumentTypesOf(InvocationOnMock invocation) {
903         Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();
904         if (parameterTypes.length == 0) {
905             return new StringBuilder("the method has no arguments.\n");
906         }
907 
908         StringBuilder stringBuilder =
909                 new StringBuilder("the possible argument indexes for this method are :\n");
910         for (int i = 0, parameterTypesLength = parameterTypes.length;
911                 i < parameterTypesLength;
912                 i++) {
913             stringBuilder.append("    [").append(i);
914 
915             if (invocation.getMethod().isVarArgs() && i == parameterTypesLength - 1) {
916                 stringBuilder
917                         .append("+] ")
918                         .append(parameterTypes[i].getComponentType().getSimpleName())
919                         .append("  <- Vararg")
920                         .append("\n");
921             } else {
922                 stringBuilder.append("] ").append(parameterTypes[i].getSimpleName()).append("\n");
923             }
924         }
925         return stringBuilder;
926     }
927 
wrongTypeOfArgumentToReturn( InvocationOnMock invocation, String expectedType, Class<?> actualType, int argumentIndex)928     public static MockitoException wrongTypeOfArgumentToReturn(
929             InvocationOnMock invocation,
930             String expectedType,
931             Class<?> actualType,
932             int argumentIndex) {
933         return new WrongTypeOfReturnValue(
934                 join(
935                         "The argument of type '"
936                                 + actualType.getSimpleName()
937                                 + "' cannot be returned because the following ",
938                         "method should return the type '" + expectedType + "'",
939                         " -> "
940                                 + MockUtil.getMockName(invocation.getMock())
941                                 + "."
942                                 + invocation.getMethod().getName()
943                                 + "()",
944                         "",
945                         "The reason for this error can be :",
946                         "1. The wanted argument position is incorrect.",
947                         "2. The answer is used on the wrong interaction.",
948                         "",
949                         "Position of the wanted argument is "
950                                 + argumentIndex
951                                 + " and "
952                                 + possibleArgumentTypesOf(invocation),
953                         "***",
954                         "However if you're still unsure why you're getting above error read on.",
955                         "Due to the nature of the syntax above problem might occur because:",
956                         "1. This exception *might* occur in wrongly written multi-threaded tests.",
957                         "   Please refer to Mockito FAQ on limitations of concurrency testing.",
958                         "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",
959                         "   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",
960                         ""));
961     }
962 
defaultAnswerDoesNotAcceptNullParameter()963     public static MockitoException defaultAnswerDoesNotAcceptNullParameter() {
964         return new MockitoException("defaultAnswer() does not accept null parameter");
965     }
966 
serializableWontWorkForObjectsThatDontImplementSerializable( Class<?> classToMock)967     public static MockitoException serializableWontWorkForObjectsThatDontImplementSerializable(
968             Class<?> classToMock) {
969         return new MockitoException(
970                 join(
971                         "You are using the setting 'withSettings().serializable()' however the type you are trying to mock '"
972                                 + classToMock.getSimpleName()
973                                 + "'",
974                         "do not implement Serializable AND do not have a no-arg constructor.",
975                         "This combination is requested, otherwise you will get an 'java.io.InvalidClassException' when the mock will be serialized",
976                         "",
977                         "Also note that as requested by the Java serialization specification, the whole hierarchy need to implements Serializable,",
978                         "i.e. the top-most superclass has to implements Serializable.",
979                         ""));
980     }
981 
delegatedMethodHasWrongReturnType( Method mockMethod, Method delegateMethod, Object mock, Object delegate)982     public static MockitoException delegatedMethodHasWrongReturnType(
983             Method mockMethod, Method delegateMethod, Object mock, Object delegate) {
984         return new MockitoException(
985                 join(
986                         "Methods called on delegated instance must have compatible return types with the mock.",
987                         "When calling: " + mockMethod + " on mock: " + MockUtil.getMockName(mock),
988                         "return type should be: "
989                                 + mockMethod.getReturnType().getSimpleName()
990                                 + ", but was: "
991                                 + delegateMethod.getReturnType().getSimpleName(),
992                         "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
993                         "(delegate instance had type: "
994                                 + delegate.getClass().getSimpleName()
995                                 + ")"));
996     }
997 
delegatedMethodDoesNotExistOnDelegate( Method mockMethod, Object mock, Object delegate)998     public static MockitoException delegatedMethodDoesNotExistOnDelegate(
999             Method mockMethod, Object mock, Object delegate) {
1000         return new MockitoException(
1001                 join(
1002                         "Methods called on mock must exist in delegated instance.",
1003                         "When calling: " + mockMethod + " on mock: " + MockUtil.getMockName(mock),
1004                         "no such method was found.",
1005                         "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
1006                         "(delegate instance had type: "
1007                                 + delegate.getClass().getSimpleName()
1008                                 + ")"));
1009     }
1010 
usingConstructorWithFancySerializable(SerializableMode mode)1011     public static MockitoException usingConstructorWithFancySerializable(SerializableMode mode) {
1012         return new MockitoException(
1013                 "Mocks instantiated with constructor cannot be combined with "
1014                         + mode
1015                         + " serialization mode.");
1016     }
1017 
cannotCreateTimerWithNegativeDurationTime(long durationMillis)1018     public static MockitoException cannotCreateTimerWithNegativeDurationTime(long durationMillis) {
1019         return new FriendlyReminderException(
1020                 join(
1021                         "",
1022                         "Don't panic! I'm just a friendly reminder!",
1023                         "It is impossible for time to go backward, therefore...",
1024                         "You cannot put negative value of duration: (" + durationMillis + ")",
1025                         "as argument of timer methods (after(), timeout())",
1026                         ""));
1027     }
1028 
notAnException()1029     public static MockitoException notAnException() {
1030         return new MockitoException(
1031                 join(
1032                         "Exception type cannot be null.",
1033                         "This may happen with doThrow(Class)|thenThrow(Class) family of methods if passing null parameter."));
1034     }
1035 
inlineClassWithoutUnboxImpl( Class<?> inlineClass, Exception details)1036     public static MockitoException inlineClassWithoutUnboxImpl(
1037             Class<?> inlineClass, Exception details) {
1038         return new MockitoException(
1039                 join(
1040                         "Kotlin inline class should have unbox-impl() method,",
1041                         "but " + inlineClass + " does not."),
1042                 details);
1043     }
1044 
formatUnncessaryStubbingException( Class<?> testClass, Collection<Invocation> unnecessaryStubbings)1045     public static UnnecessaryStubbingException formatUnncessaryStubbingException(
1046             Class<?> testClass, Collection<Invocation> unnecessaryStubbings) {
1047         StringBuilder stubbings = new StringBuilder();
1048         int count = 1;
1049         for (Invocation u : unnecessaryStubbings) {
1050             stubbings.append("\n  ").append(count++).append(". ").append(u.getLocation());
1051         }
1052         String heading =
1053                 (testClass != null)
1054                         ? "Unnecessary stubbings detected in test class: "
1055                                 + testClass.getSimpleName()
1056                         : "Unnecessary stubbings detected.";
1057 
1058         return new UnnecessaryStubbingException(
1059                 join(
1060                         heading,
1061                         "Clean & maintainable test code requires zero unnecessary code.",
1062                         "Following stubbings are unnecessary (click to navigate to relevant line of code):"
1063                                 + stubbings,
1064                         "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class."));
1065     }
1066 
unncessaryStubbingException(List<Invocation> unused)1067     public static void unncessaryStubbingException(List<Invocation> unused) {
1068         throw formatUnncessaryStubbingException(null, unused);
1069     }
1070 
potentialStubbingProblem( Invocation actualInvocation, Collection<Invocation> argMismatchStubbings)1071     public static void potentialStubbingProblem(
1072             Invocation actualInvocation, Collection<Invocation> argMismatchStubbings) {
1073         StringBuilder stubbings = new StringBuilder();
1074         int count = 1;
1075         for (Invocation s : argMismatchStubbings) {
1076             stubbings.append("    ").append(count++).append(". ").append(s);
1077             stubbings.append("\n      ").append(s.getLocation()).append("\n");
1078         }
1079         stubbings.deleteCharAt(stubbings.length() - 1); // remove trailing end of line
1080 
1081         throw new PotentialStubbingProblem(
1082                 join(
1083                         "Strict stubbing argument mismatch. Please check:",
1084                         " - this invocation of '"
1085                                 + actualInvocation.getMethod().getName()
1086                                 + "' method:",
1087                         "    " + actualInvocation,
1088                         "    " + actualInvocation.getLocation(),
1089                         " - has following stubbing(s) with different arguments:",
1090                         stubbings,
1091                         "Typically, stubbing argument mismatch indicates user mistake when writing tests.",
1092                         "Mockito fails early so that you can debug potential problem easily.",
1093                         "However, there are legit scenarios when this exception generates false negative signal:",
1094                         "  - stubbing the same method multiple times using 'given().will()' or 'when().then()' API",
1095                         "    Please use 'will().given()' or 'doReturn().when()' API for stubbing.",
1096                         "  - stubbed method is intentionally invoked with different arguments by code under test",
1097                         "    Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).",
1098                         "For more information see javadoc for PotentialStubbingProblem class."));
1099     }
1100 
redundantMockitoListener(String listenerType)1101     public static void redundantMockitoListener(String listenerType) {
1102         throw new RedundantListenerException(
1103                 join(
1104                         "Problems adding Mockito listener.",
1105                         "Listener of type '"
1106                                 + listenerType
1107                                 + "' has already been added and not removed.",
1108                         "It indicates that previous listener was not removed according to the API.",
1109                         "When you add a listener, don't forget to remove the listener afterwards:",
1110                         "  Mockito.framework().removeListener(myListener);",
1111                         "For more information, see the javadoc for RedundantListenerException class."));
1112     }
1113 
unfinishedMockingSession()1114     public static void unfinishedMockingSession() {
1115         throw new UnfinishedMockingSessionException(
1116                 join(
1117                         "Unfinished mocking session detected.",
1118                         "Previous MockitoSession was not concluded with 'finishMocking()'.",
1119                         "For examples of correct usage see javadoc for MockitoSession class."));
1120     }
1121 
missingByteBuddyDependency(Throwable t)1122     public static void missingByteBuddyDependency(Throwable t) {
1123         if (t instanceof NoClassDefFoundError
1124                 && t.getMessage() != null
1125                 && t.getMessage().startsWith("net/bytebuddy/")) {
1126             throw new MockitoInitializationException(
1127                     join(
1128                             "It seems like you are running Mockito with an incomplete or inconsistent class path. Byte Buddy could not be loaded.",
1129                             "",
1130                             "Byte Buddy is available on Maven Central as 'net.bytebuddy:byte-buddy' with the module name 'net.bytebuddy'.",
1131                             "For the inline mock maker, 'net.bytebuddy:byte-buddy-agent' with the module name 'net.bytebuddy.agent' is also required.",
1132                             "Normally, your IDE or build tool (such as Maven or Gradle) should take care of your class path completion but "),
1133                     t);
1134         }
1135     }
1136 }
1137