How to use RedundantListenerException method of org.mockito.exceptions.misusing.WrongTypeOfReturnValue class

Best Mockito code snippet using org.mockito.exceptions.misusing.WrongTypeOfReturnValue.RedundantListenerException

Source:Reporter.java Github

copy

Full Screen

...17import org.mockito.exceptions.misusing.MissingMethodInvocationException;18import org.mockito.exceptions.misusing.NotAMockException;19import org.mockito.exceptions.misusing.NullInsteadOfMockException;20import org.mockito.exceptions.misusing.PotentialStubbingProblem;21import org.mockito.exceptions.misusing.RedundantListenerException;22import org.mockito.exceptions.misusing.UnfinishedMockingSessionException;23import org.mockito.exceptions.misusing.UnfinishedStubbingException;24import org.mockito.exceptions.misusing.UnfinishedVerificationException;25import org.mockito.exceptions.misusing.UnnecessaryStubbingException;26import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;27import org.mockito.exceptions.verification.NeverWantedButInvoked;28import org.mockito.exceptions.verification.NoInteractionsWanted;29import org.mockito.exceptions.verification.SmartNullPointerException;30import org.mockito.exceptions.verification.TooLittleActualInvocations;31import org.mockito.exceptions.verification.TooManyActualInvocations;32import org.mockito.exceptions.verification.VerificationInOrderFailure;33import org.mockito.exceptions.verification.WantedButNotInvoked;34import org.mockito.internal.debugging.LocationImpl;35import org.mockito.internal.exceptions.util.ScenarioPrinter;36import org.mockito.internal.junit.ExceptionFactory;37import org.mockito.internal.matchers.LocalizedMatcher;38import org.mockito.internal.util.MockUtil;39import org.mockito.invocation.DescribedInvocation;40import org.mockito.invocation.Invocation;41import org.mockito.invocation.InvocationOnMock;42import org.mockito.invocation.Location;43import org.mockito.listeners.InvocationListener;44import org.mockito.mock.MockName;45import org.mockito.mock.SerializableMode;46import static org.mockito.internal.reporting.Pluralizer.pluralize;47import static org.mockito.internal.reporting.Pluralizer.were_exactly_x_interactions;48import static org.mockito.internal.util.StringUtil.join;49/​**50 * Reports verification and misusing errors.51 * <p>52 * One of the key points of mocking library is proper verification/​exception53 * messages. All messages in one place makes it easier to tune and amend them.54 * <p>55 * Reporter can be injected and therefore is easily testable.56 * <p>57 * Generally, exception messages are full of line breaks to make them easy to58 * read (xunit plugins take only fraction of screen on modern IDEs).59 */​60public class Reporter {61 private final static String NON_PUBLIC_PARENT = "Mocking methods declared on non-public parent classes is not supported.";62 private Reporter() {63 }64 public static MockitoException checkedExceptionInvalid(Throwable t) {65 return new MockitoException(join(66 "Checked exception is invalid for this method!",67 "Invalid: " + t68 ));69 }70 public static MockitoException cannotStubWithNullThrowable() {71 return new MockitoException(join(72 "Cannot stub with null throwable!"73 ));74 }75 public static MockitoException unfinishedStubbing(Location location) {76 return new UnfinishedStubbingException(join(77 "Unfinished stubbing detected here:",78 location,79 "",80 "E.g. thenReturn() may be missing.",81 "Examples of correct stubbing:",82 " when(mock.isOk()).thenReturn(true);",83 " when(mock.isOk()).thenThrow(exception);",84 " doThrow(exception).when(mock).someVoidMethod();",85 "Hints:",86 " 1. missing thenReturn()",87 " 2. you are trying to stub a final method, which is not supported",88 " 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed",89 ""90 ));91 }92 public static MockitoException incorrectUseOfApi() {93 return new MockitoException(join(94 "Incorrect use of API detected here:",95 new LocationImpl(),96 "",97 "You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.",98 "Examples of correct usage:",99 " when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);",100 " when(mock.isOk()).thenReturn(true, false).thenThrow(exception);",101 ""102 ));103 }104 public static MockitoException missingMethodInvocation() {105 return new MissingMethodInvocationException(join(106 "when() requires an argument which has to be 'a method call on a mock'.",107 "For example:",108 " when(mock.getArticles()).thenReturn(articles);",109 "",110 "Also, this error might show up because:",111 "1. you stub either of: final/​private/​equals()/​hashCode() methods.",112 " Those methods *cannot* be stubbed/​verified.",113 " " + NON_PUBLIC_PARENT,114 "2. inside when() you don't call method on mock but on some other object.",115 ""116 ));117 }118 public static MockitoException unfinishedVerificationException(Location location) {119 return new UnfinishedVerificationException(join(120 "Missing method call for verify(mock) here:",121 location,122 "",123 "Example of correct verification:",124 " verify(mock).doSomething()",125 "",126 "Also, this error might show up because you verify either of: final/​private/​equals()/​hashCode() methods.",127 "Those methods *cannot* be stubbed/​verified.",128 NON_PUBLIC_PARENT,129 ""130 ));131 }132 public static MockitoException notAMockPassedToVerify(Class<?> type) {133 return new NotAMockException(join(134 "Argument passed to verify() is of type " + type.getSimpleName() + " and is not a mock!",135 "Make sure you place the parenthesis correctly!",136 "See the examples of correct verifications:",137 " verify(mock).someMethod();",138 " verify(mock, times(10)).someMethod();",139 " verify(mock, atLeastOnce()).someMethod();"140 ));141 }142 public static MockitoException nullPassedToVerify() {143 return new NullInsteadOfMockException(join(144 "Argument passed to verify() should be a mock but is null!",145 "Examples of correct verifications:",146 " verify(mock).someMethod();",147 " verify(mock, times(10)).someMethod();",148 " verify(mock, atLeastOnce()).someMethod();",149 " not: verify(mock.someMethod());",150 "Also, if you use @Mock annotation don't miss initMocks()"151 ));152 }153 public static MockitoException notAMockPassedToWhenMethod() {154 return new NotAMockException(join(155 "Argument passed to when() is not a mock!",156 "Example of correct stubbing:",157 " doThrow(new RuntimeException()).when(mock).someMethod();"158 ));159 }160 public static MockitoException nullPassedToWhenMethod() {161 return new NullInsteadOfMockException(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 initMocks()"166 ));167 }168 public static MockitoException mocksHaveToBePassedToVerifyNoMoreInteractions() {169 return new MockitoException(join(170 "Method requires argument(s)!",171 "Pass mocks that should be verified, e.g:",172 " verifyNoMoreInteractions(mockOne, mockTwo);",173 " verifyZeroInteractions(mockOne, mockTwo);",174 ""175 ));176 }177 public static MockitoException notAMockPassedToVerifyNoMoreInteractions() {178 return new NotAMockException(join(179 "Argument(s) passed is not a mock!",180 "Examples of correct verifications:",181 " verifyNoMoreInteractions(mockOne, mockTwo);",182 " verifyZeroInteractions(mockOne, mockTwo);",183 ""184 ));185 }186 public static MockitoException nullPassedToVerifyNoMoreInteractions() {187 return new NullInsteadOfMockException(join(188 "Argument(s) passed is null!",189 "Examples of correct verifications:",190 " verifyNoMoreInteractions(mockOne, mockTwo);",191 " verifyZeroInteractions(mockOne, mockTwo);"192 ));193 }194 public static MockitoException notAMockPassedWhenCreatingInOrder() {195 return new NotAMockException(join(196 "Argument(s) passed is not a mock!",197 "Pass mocks that require verification in order.",198 "For example:",199 " InOrder inOrder = inOrder(mockOne, mockTwo);"200 ));201 }202 public static MockitoException nullPassedWhenCreatingInOrder() {203 return new NullInsteadOfMockException(join(204 "Argument(s) passed is null!",205 "Pass mocks that require verification in order.",206 "For example:",207 " InOrder inOrder = inOrder(mockOne, mockTwo);"208 ));209 }210 public static MockitoException mocksHaveToBePassedWhenCreatingInOrder() {211 return new MockitoException(join(212 "Method requires argument(s)!",213 "Pass mocks that require verification in order.",214 "For example:",215 " InOrder inOrder = inOrder(mockOne, mockTwo);"216 ));217 }218 public static MockitoException inOrderRequiresFamiliarMock() {219 return new MockitoException(join(220 "InOrder can only verify mocks that were passed in during creation of InOrder.",221 "For example:",222 " InOrder inOrder = inOrder(mockOne);",223 " inOrder.verify(mockOne).doStuff();"224 ));225 }226 public static MockitoException invalidUseOfMatchers(int expectedMatchersCount, List<LocalizedMatcher> recordedMatchers) {227 return new InvalidUseOfMatchersException(join(228 "Invalid use of argument matchers!",229 expectedMatchersCount + " matchers expected, " + recordedMatchers.size() + " recorded:" +230 locationsOf(recordedMatchers),231 "",232 "This exception may occur if matchers are combined with raw values:",233 " /​/​incorrect:",234 " someMethod(anyObject(), \"raw String\");",235 "When using matchers, all arguments have to be provided by matchers.",236 "For example:",237 " /​/​correct:",238 " someMethod(anyObject(), eq(\"String by matcher\"));",239 "",240 "For more info see javadoc for Matchers class.",241 ""242 ));243 }244 public static MockitoException incorrectUseOfAdditionalMatchers(String additionalMatcherName, int expectedSubMatchersCount, Collection<LocalizedMatcher> matcherStack) {245 return new InvalidUseOfMatchersException(join(246 "Invalid use of argument matchers inside additional matcher " + additionalMatcherName + " !",247 new LocationImpl(),248 "",249 expectedSubMatchersCount + " sub matchers expected, " + matcherStack.size() + " recorded:",250 locationsOf(matcherStack),251 "",252 "This exception may occur if matchers are combined with raw values:",253 " /​/​incorrect:",254 " someMethod(AdditionalMatchers.and(isNotNull(), \"raw String\");",255 "When using matchers, all arguments have to be provided by matchers.",256 "For example:",257 " /​/​correct:",258 " someMethod(AdditionalMatchers.and(isNotNull(), eq(\"raw String\"));",259 "",260 "For more info see javadoc for Matchers and AdditionalMatchers classes.",261 ""262 ));263 }264 public static MockitoException stubPassedToVerify() {265 return new CannotVerifyStubOnlyMock(join(266 "Argument passed to verify() is a stubOnly() mock, not a full blown mock!",267 "If you intend to verify invocations on a mock, don't use stubOnly() in its MockSettings."268 ));269 }270 public static MockitoException reportNoSubMatchersFound(String additionalMatcherName) {271 return new InvalidUseOfMatchersException(join(272 "No matchers found for additional matcher " + additionalMatcherName,273 new LocationImpl(),274 ""275 ));276 }277 private static Object locationsOf(Collection<LocalizedMatcher> matchers) {278 List<String> description = new ArrayList<String>();279 for (LocalizedMatcher matcher : matchers)280 description.add(matcher.getLocation().toString());281 return join(description.toArray());282 }283 public static AssertionError argumentsAreDifferent(String wanted, String actual, Location actualLocation) {284 String message = join("Argument(s) are different! Wanted:",285 wanted,286 new LocationImpl(),287 "Actual invocation has different arguments:",288 actual,289 actualLocation,290 ""291 );292 return ExceptionFactory.createArgumentsAreDifferentException(message, wanted, actual);293 }294 public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted) {295 return new WantedButNotInvoked(createWantedButNotInvokedMessage(wanted));296 }297 public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted, List<? extends DescribedInvocation> invocations) {298 String allInvocations;299 if (invocations.isEmpty()) {300 allInvocations = "Actually, there were zero interactions with this mock.\n";301 } else {302 StringBuilder sb = new StringBuilder(303 "\nHowever, there " + were_exactly_x_interactions(invocations.size()) + " with this mock:\n");304 for (DescribedInvocation i : invocations) {305 sb.append(i.toString())306 .append("\n")307 .append(i.getLocation())308 .append("\n\n");309 }310 allInvocations = sb.toString();311 }312 String message = createWantedButNotInvokedMessage(wanted);313 return new WantedButNotInvoked(message + allInvocations);314 }315 private static String createWantedButNotInvokedMessage(DescribedInvocation wanted) {316 return join(317 "Wanted but not invoked:",318 wanted.toString(),319 new LocationImpl(),320 ""321 );322 }323 public static MockitoAssertionError wantedButNotInvokedInOrder(DescribedInvocation wanted, DescribedInvocation previous) {324 return new VerificationInOrderFailure(join(325 "Verification in order failure",326 "Wanted but not invoked:",327 wanted.toString(),328 new LocationImpl(),329 "Wanted anywhere AFTER following interaction:",330 previous.toString(),331 previous.getLocation(),332 ""333 ));334 }335 public static MockitoAssertionError tooManyActualInvocations(int wantedCount, int actualCount, DescribedInvocation wanted, List<Location> locations) {336 String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, locations);337 return new TooManyActualInvocations(message);338 }339 private static String createTooManyInvocationsMessage(int wantedCount, int actualCount, DescribedInvocation wanted,340 List<Location> invocations) {341 return join(342 wanted.toString(),343 "Wanted " + pluralize(wantedCount) + ":",344 new LocationImpl(),345 "But was " + pluralize(actualCount) + ":",346 createAllLocationsMessage(invocations),347 ""348 );349 }350 public static MockitoAssertionError neverWantedButInvoked(DescribedInvocation wanted, List<Location> invocations) {351 return new NeverWantedButInvoked(join(352 wanted.toString(),353 "Never wanted here:",354 new LocationImpl(),355 "But invoked here:",356 createAllLocationsMessage(invocations)357 ));358 }359 public static MockitoAssertionError tooManyActualInvocationsInOrder(int wantedCount, int actualCount, DescribedInvocation wanted, List<Location> invocations) {360 String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, invocations);361 return new VerificationInOrderFailure(join(362 "Verification in order failure:" + message363 ));364 }365 private static String createAllLocationsMessage(List<Location> locations) {366 if (locations == null) {367 return "\n";368 }369 StringBuilder sb = new StringBuilder();370 for (Location location : locations) {371 sb.append(location).append("\n");372 }373 return sb.toString();374 }375 private static String createTooLittleInvocationsMessage(org.mockito.internal.reporting.Discrepancy discrepancy,376 DescribedInvocation wanted,377 List<Location> locations) {378 return join(379 wanted.toString(),380 "Wanted " + discrepancy.getPluralizedWantedCount() + (discrepancy.getWantedCount() == 0 ? "." : ":"),381 new LocationImpl(),382 "But was " + discrepancy.getPluralizedActualCount() + (discrepancy.getActualCount() == 0 ? "." : ":"),383 createAllLocationsMessage(locations)384 );385 }386 public static MockitoAssertionError tooLittleActualInvocations(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> allLocations) {387 String message = createTooLittleInvocationsMessage(discrepancy, wanted, allLocations);388 return new TooLittleActualInvocations(message);389 }390 public static MockitoAssertionError tooLittleActualInvocationsInOrder(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> locations) {391 String message = createTooLittleInvocationsMessage(discrepancy, wanted, locations);392 return new VerificationInOrderFailure(join(393 "Verification in order failure:" + message394 ));395 }396 public static MockitoAssertionError noMoreInteractionsWanted(Invocation undesired, List<VerificationAwareInvocation> invocations) {397 ScenarioPrinter scenarioPrinter = new ScenarioPrinter();398 String scenario = scenarioPrinter.print(invocations);399 return new NoInteractionsWanted(join(400 "No interactions wanted here:",401 new LocationImpl(),402 "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",403 undesired.getLocation(),404 scenario405 ));406 }407 public static MockitoAssertionError noMoreInteractionsWantedInOrder(Invocation undesired) {408 return new VerificationInOrderFailure(join(409 "No interactions wanted here:",410 new LocationImpl(),411 "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",412 undesired.getLocation()413 ));414 }415 public static MockitoException cannotMockClass(Class<?> clazz, String reason) {416 return new MockitoException(join(417 "Cannot mock/​spy " + clazz.toString(),418 "Mockito cannot mock/​spy because :",419 " - " + reason420 ));421 }422 public static MockitoException cannotStubVoidMethodWithAReturnValue(String methodName) {423 return new CannotStubVoidMethodWithReturnValue(join(424 "'" + methodName + "' is a *void method* and it *cannot* be stubbed with a *return value*!",425 "Voids are usually stubbed with Throwables:",426 " doThrow(exception).when(mock).someVoidMethod();",427 "If you need to set the void method to do nothing you can use:",428 " doNothing().when(mock).someVoidMethod();",429 "For more information, check out the javadocs for Mockito.doNothing().",430 "***",431 "If you're unsure why you're getting above error read on.",432 "Due to the nature of the syntax above problem might occur because:",433 "1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.",434 "2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/​stub final methods.",435 "3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",436 " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",437 "4. " + NON_PUBLIC_PARENT,438 ""439 ));440 }441 public static MockitoException onlyVoidMethodsCanBeSetToDoNothing() {442 return new MockitoException(join(443 "Only void methods can doNothing()!",444 "Example of correct use of doNothing():",445 " doNothing().",446 " doThrow(new RuntimeException())",447 " .when(mock).someVoidMethod();",448 "Above means:",449 "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called"450 ));451 }452 public static MockitoException wrongTypeOfReturnValue(String expectedType, String actualType, String methodName) {453 return new WrongTypeOfReturnValue(join(454 actualType + " cannot be returned by " + methodName + "()",455 methodName + "() should return " + expectedType,456 "***",457 "If you're unsure why you're getting above error read on.",458 "Due to the nature of the syntax above problem might occur because:",459 "1. This exception *might* occur in wrongly written multi-threaded tests.",460 " Please refer to Mockito FAQ on limitations of concurrency testing.",461 "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",462 " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",463 ""464 ));465 }466 public static MockitoException wrongTypeReturnedByDefaultAnswer(Object mock, String expectedType, String actualType, String methodName) {467 return new WrongTypeOfReturnValue(join(468 "Default answer returned a result with the wrong type:",469 actualType + " cannot be returned by " + methodName + "()",470 methodName + "() should return " + expectedType,471 "",472 "The default answer of " + safelyGetMockName(mock) + " that was configured on the mock is probably incorrectly implemented.",473 ""474 ));475 }476 public static MockitoAssertionError wantedAtMostX(int maxNumberOfInvocations, int foundSize) {477 return new MockitoAssertionError(join("Wanted at most " + pluralize(maxNumberOfInvocations) + " but was " + foundSize));478 }479 public static MockitoException misplacedArgumentMatcher(List<LocalizedMatcher> lastMatchers) {480 return new InvalidUseOfMatchersException(join(481 "Misplaced or misused argument matcher detected here:",482 locationsOf(lastMatchers),483 "",484 "You cannot use argument matchers outside of verification or stubbing.",485 "Examples of correct usage of argument matchers:",486 " when(mock.get(anyInt())).thenReturn(null);",487 " doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());",488 " verify(mock).someMethod(contains(\"foo\"))",489 "",490 "This message may appear after an NullPointerException if the last matcher is returning an object ",491 "like any() but the stubbed method signature expect a primitive argument, in this case,",492 "use primitive alternatives.",493 " when(mock.get(any())); /​/​ bad use, will raise NPE",494 " when(mock.get(anyInt())); /​/​ correct usage use",495 "",496 "Also, this error might show up because you use argument matchers with methods that cannot be mocked.",497 "Following methods *cannot* be stubbed/​verified: final/​private/​equals()/​hashCode().",498 NON_PUBLIC_PARENT,499 ""500 ));501 }502 public static MockitoException smartNullPointerException(String invocation, Location location) {503 return new SmartNullPointerException(join(504 "You have a NullPointerException here:",505 new LocationImpl(),506 "because this method call was *not* stubbed correctly:",507 location,508 invocation,509 ""510 ));511 }512 public static MockitoException noArgumentValueWasCaptured() {513 return new MockitoException(join(514 "No argument value was captured!",515 "You might have forgotten to use argument.capture() in verify()...",516 "...or you used capture() in stubbing but stubbed method was not called.",517 "Be aware that it is recommended to use capture() only with verify()",518 "",519 "Examples of correct argument capturing:",520 " ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);",521 " verify(mock).doSomething(argument.capture());",522 " assertEquals(\"John\", argument.getValue().getName());",523 ""524 ));525 }526 public static MockitoException extraInterfacesDoesNotAcceptNullParameters() {527 return new MockitoException(join(528 "extraInterfaces() does not accept null parameters."529 ));530 }531 public static MockitoException extraInterfacesAcceptsOnlyInterfaces(Class<?> wrongType) {532 return new MockitoException(join(533 "extraInterfaces() accepts only interfaces.",534 "You passed following type: " + wrongType.getSimpleName() + " which is not an interface."535 ));536 }537 public static MockitoException extraInterfacesCannotContainMockedType(Class<?> wrongType) {538 return new MockitoException(join(539 "extraInterfaces() does not accept the same type as the mocked type.",540 "You mocked following type: " + wrongType.getSimpleName(),541 "and you passed the same very interface to the extraInterfaces()"542 ));543 }544 public static MockitoException extraInterfacesRequiresAtLeastOneInterface() {545 return new MockitoException(join(546 "extraInterfaces() requires at least one interface."547 ));548 }549 public static MockitoException mockedTypeIsInconsistentWithSpiedInstanceType(Class<?> mockedType, Object spiedInstance) {550 return new MockitoException(join(551 "Mocked type must be the same as the type of your spied instance.",552 "Mocked type must be: " + spiedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(),553 " /​/​correct spying:",554 " spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );",555 " /​/​incorrect - types don't match:",556 " spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );"557 ));558 }559 public static MockitoException cannotCallAbstractRealMethod() {560 return new MockitoException(join(561 "Cannot call abstract real method on java object!",562 "Calling real methods is only possible when mocking non abstract method.",563 " /​/​correct example:",564 " when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();"565 ));566 }567 public static MockitoException cannotVerifyToString() {568 return new MockitoException(join(569 "Mockito cannot verify toString()",570 "toString() is too often used behind of scenes (i.e. during String concatenation, in IDE debugging views). " +571 "Verifying it may give inconsistent or hard to understand results. " +572 "Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)",573 "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases."574 ));575 }576 public static MockitoException moreThanOneAnnotationNotAllowed(String fieldName) {577 return new MockitoException("You cannot have more than one Mockito annotation on a field!\n" +578 "The field '" + fieldName + "' has multiple Mockito annotations.\n" +579 "For info how to use annotations see examples in javadoc for MockitoAnnotations class.");580 }581 public static MockitoException unsupportedCombinationOfAnnotations(String undesiredAnnotationOne, String undesiredAnnotationTwo) {582 return new MockitoException("This combination of annotations is not permitted on a single field:\n" +583 "@" + undesiredAnnotationOne + " and @" + undesiredAnnotationTwo);584 }585 public static MockitoException cannotInitializeForSpyAnnotation(String fieldName, Exception details) {586 return new MockitoException(join("Cannot instantiate a @Spy for '" + fieldName + "' field.",587 "You haven't provided the instance for spying at field declaration so I tried to construct the instance.",588 "However, I failed because: " + details.getMessage(),589 "Examples of correct usage of @Spy:",590 " @Spy List mock = new LinkedList();",591 " @Spy Foo foo; /​/​only if Foo has parameterless constructor",592 " /​/​also, don't forget about MockitoAnnotations.initMocks();",593 ""), details);594 }595 public static MockitoException cannotInitializeForInjectMocksAnnotation(String fieldName, String causeMessage) {596 return new MockitoException(join("Cannot instantiate @InjectMocks field named '" + fieldName + "'! Cause: "+causeMessage,597 "You haven't provided the instance at field declaration so I tried to construct the instance.",598 "Examples of correct usage of @InjectMocks:",599 " @InjectMocks Service service = new Service();",600 " @InjectMocks Service service;",601 " /​/​and... don't forget about some @Mocks for injection :)",602 ""));603 }604 public static MockitoException atMostAndNeverShouldNotBeUsedWithTimeout() {605 return new FriendlyReminderException(join("",606 "Don't panic! I'm just a friendly reminder!",607 "timeout() should not be used with atMost() or never() because...",608 "...it does not make much sense - the test would have passed immediately in concurrency",609 "We kept this method only to avoid compilation errors when upgrading Mockito.",610 "In future release we will remove timeout(x).atMost(y) from the API.",611 "If you want to find out more please refer to issue 235",612 ""));613 }614 public static MockitoException fieldInitialisationThrewException(Field field, Throwable details) {615 return new MockitoException(join(616 "Cannot instantiate @InjectMocks field named '" + field.getName() + "' of type '" + field.getType() + "'.",617 "You haven't provided the instance at field declaration so I tried to construct the instance.",618 "However the constructor or the initialization block threw an exception : " + details.getMessage(),619 ""), details);620 }621 public static MockitoException methodDoesNotAcceptParameter(String method, String parameter) {622 return new MockitoException(method + "() does not accept " + parameter + " See the Javadoc.");623 }624 public static MockitoException invocationListenersRequiresAtLeastOneListener() {625 return new MockitoException("invocationListeners() requires at least one listener");626 }627 public static MockitoException invocationListenerThrewException(InvocationListener listener, Throwable listenerThrowable) {628 return new MockitoException(join(629 "The invocation listener with type " + listener.getClass().getName(),630 "threw an exception : " + listenerThrowable.getClass().getName() + listenerThrowable.getMessage()), listenerThrowable);631 }632 public static MockitoException cannotInjectDependency(Field field, Object matchingMock, Exception details) {633 return new MockitoException(join(634 "Mockito couldn't inject mock dependency '" + safelyGetMockName(matchingMock) + "' on field ",635 "'" + field + "'",636 "whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.",637 "Also I failed because: " + exceptionCauseMessageIfAvailable(details),638 ""639 ), details);640 }641 private static String exceptionCauseMessageIfAvailable(Exception details) {642 if (details.getCause() == null) {643 return details.getMessage();644 }645 return details.getCause().getMessage();646 }647 public static MockitoException mockedTypeIsInconsistentWithDelegatedInstanceType(Class<?> mockedType, Object delegatedInstance) {648 return new MockitoException(join(649 "Mocked type must be the same as the type of your delegated instance.",650 "Mocked type must be: " + delegatedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(),651 " /​/​correct delegate:",652 " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new ArrayList()<- );",653 " /​/​incorrect - types don't match:",654 " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new HashSet()<- );"655 ));656 }657 public static MockitoException spyAndDelegateAreMutuallyExclusive() {658 return new MockitoException(join(659 "Settings should not define a spy instance and a delegated instance at the same time."660 ));661 }662 public static MockitoException invalidArgumentRangeAtIdentityAnswerCreationTime() {663 return new MockitoException(join(664 "Invalid argument index.",665 "The index need to be a positive number that indicates the position of the argument to return.",666 "However it is possible to use the -1 value to indicates that the last argument should be",667 "returned."));668 }669 public static MockitoException invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) {670 return new MockitoException(join(671 "Invalid argument index for the current invocation of method : ",672 " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",673 "",674 (willReturnLastParameter ?675 "Last parameter wanted" :676 "Wanted parameter at position " + argumentIndex) + " but " + possibleArgumentTypesOf(invocation),677 "The index need to be a positive number that indicates a valid position of the argument in the invocation.",678 "However it is possible to use the -1 value to indicates that the last argument should be returned.",679 ""680 ));681 }682 private static StringBuilder possibleArgumentTypesOf(InvocationOnMock invocation) {683 Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();684 if (parameterTypes.length == 0) {685 return new StringBuilder("the method has no arguments.\n");686 }687 StringBuilder stringBuilder = new StringBuilder("the possible argument indexes for this method are :\n");688 for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) {689 stringBuilder.append(" [").append(i);690 if (invocation.getMethod().isVarArgs() && i == parameterTypesLength - 1) {691 stringBuilder.append("+] ").append(parameterTypes[i].getComponentType().getSimpleName()).append(" <- Vararg").append("\n");692 } else {693 stringBuilder.append("] ").append(parameterTypes[i].getSimpleName()).append("\n");694 }695 }696 return stringBuilder;697 }698 public static MockitoException wrongTypeOfArgumentToReturn(InvocationOnMock invocation, String expectedType, Class<?> actualType, int argumentIndex) {699 return new WrongTypeOfReturnValue(join(700 "The argument of type '" + actualType.getSimpleName() + "' cannot be returned because the following ",701 "method should return the type '" + expectedType + "'",702 " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",703 "",704 "The reason for this error can be :",705 "1. The wanted argument position is incorrect.",706 "2. The answer is used on the wrong interaction.",707 "",708 "Position of the wanted argument is " + argumentIndex + " and " + possibleArgumentTypesOf(invocation),709 "***",710 "However if you're still unsure why you're getting above error read on.",711 "Due to the nature of the syntax above problem might occur because:",712 "1. This exception *might* occur in wrongly written multi-threaded tests.",713 " Please refer to Mockito FAQ on limitations of concurrency testing.",714 "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",715 " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",716 ""717 ));718 }719 public static MockitoException defaultAnswerDoesNotAcceptNullParameter() {720 return new MockitoException("defaultAnswer() does not accept null parameter");721 }722 public static MockitoException serializableWontWorkForObjectsThatDontImplementSerializable(Class<?> classToMock) {723 return new MockitoException(join(724 "You are using the setting 'withSettings().serializable()' however the type you are trying to mock '" + classToMock.getSimpleName() + "'",725 "do not implement Serializable AND do not have a no-arg constructor.",726 "This combination is requested, otherwise you will get an 'java.io.InvalidClassException' when the mock will be serialized",727 "",728 "Also note that as requested by the Java serialization specification, the whole hierarchy need to implements Serializable,",729 "i.e. the top-most superclass has to implements Serializable.",730 ""731 ));732 }733 public static MockitoException delegatedMethodHasWrongReturnType(Method mockMethod, Method delegateMethod, Object mock, Object delegate) {734 return new MockitoException(join(735 "Methods called on delegated instance must have compatible return types with the mock.",736 "When calling: " + mockMethod + " on mock: " + safelyGetMockName(mock),737 "return type should be: " + mockMethod.getReturnType().getSimpleName() + ", but was: " + delegateMethod.getReturnType().getSimpleName(),738 "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",739 "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"740 ));741 }742 public static MockitoException delegatedMethodDoesNotExistOnDelegate(Method mockMethod, Object mock, Object delegate) {743 return new MockitoException(join(744 "Methods called on mock must exist in delegated instance.",745 "When calling: " + mockMethod + " on mock: " + safelyGetMockName(mock),746 "no such method was found.",747 "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",748 "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"749 ));750 }751 public static MockitoException usingConstructorWithFancySerializable(SerializableMode mode) {752 return new MockitoException("Mocks instantiated with constructor cannot be combined with " + mode + " serialization mode.");753 }754 public static MockitoException cannotCreateTimerWithNegativeDurationTime(long durationMillis) {755 return new FriendlyReminderException(join(756 "",757 "Don't panic! I'm just a friendly reminder!",758 "It is impossible for time to go backward, therefore...",759 "You cannot put negative value of duration: (" + durationMillis + ")",760 "as argument of timer methods (after(), timeout())",761 ""762 ));763 }764 public static MockitoException notAnException() {765 return new MockitoException(join(766 "Exception type cannot be null.",767 "This may happen with doThrow(Class)|thenThrow(Class) family of methods if passing null parameter."));768 }769 private static MockName safelyGetMockName(Object mock) {770 return MockUtil.getMockName(mock);771 }772 public static UnnecessaryStubbingException formatUnncessaryStubbingException(Class<?> testClass, Collection<Invocation> unnecessaryStubbings) {773 StringBuilder stubbings = new StringBuilder();774 int count = 1;775 for (Invocation u : unnecessaryStubbings) {776 stubbings.append("\n ").append(count++).append(". ").append(u.getLocation());777 }778 String heading = (testClass != null)?779 "Unnecessary stubbings detected in test class: " + testClass.getSimpleName() :780 "Unnecessary stubbings detected.";781 return new UnnecessaryStubbingException(join(782 heading,783 "Clean & maintainable test code requires zero unnecessary code.",784 "Following stubbings are unnecessary (click to navigate to relevant line of code):" + stubbings,785 "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class."786 ));787 }788 public static void unncessaryStubbingException(List<Invocation> unused) {789 throw formatUnncessaryStubbingException(null, unused);790 }791 public static void potentialStubbingProblem(792 Invocation actualInvocation, Collection<Invocation> argMismatchStubbings) {793 StringBuilder stubbings = new StringBuilder();794 int count = 1;795 for (Invocation s : argMismatchStubbings) {796 stubbings.append(" ").append(count++).append(". ").append(s);797 stubbings.append("\n ").append(s.getLocation()).append("\n");798 }799 stubbings.deleteCharAt(stubbings.length()-1); /​/​remove trailing end of line800 throw new PotentialStubbingProblem(join(801 "Strict stubbing argument mismatch. Please check:",802 " - this invocation of '" + actualInvocation.getMethod().getName() + "' method:",803 " " + actualInvocation,804 " " + actualInvocation.getLocation(),805 " - has following stubbing(s) with different arguments:",806 stubbings,807 "Typically, stubbing argument mismatch indicates user mistake when writing tests.",808 "Mockito fails early so that you can debug potential problem easily.",809 "However, there are legit scenarios when this exception generates false negative signal:",810 " - stubbing the same method multiple times using 'given().will()' or 'when().then()' API",811 " Please use 'will().given()' or 'doReturn().when()' API for stubbing.",812 " - stubbed method is intentionally invoked with different arguments by code under test",813 " Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).",814 "For more information see javadoc for PotentialStubbingProblem class."));815 }816 public static void redundantMockitoListener(String listenerType) {817 throw new RedundantListenerException(join(818 "Problems adding Mockito listener.",819 "Listener of type '" + listenerType + "' has already been added and not removed.",820 "It indicates that previous listener was not removed according to the API.",821 "When you add a listener, don't forget to remove the listener afterwards:",822 " Mockito.framework().removeListener(myListener);",823 "For more information, see the javadoc for RedundantListenerException class."));824 }825 public static void unfinishedMockingSession() {826 throw new UnfinishedMockingSessionException(join(827 "Unfinished mocking session detected.",828 "Previous MockitoSession was not concluded with 'finishMocking()'.",829 "For examples of correct usage see javadoc for MockitoSession class."));830 }831}...

Full Screen

Full Screen

RedundantListenerException

Using AI Code Generation

copy

Full Screen

1 public void test() {2 List<String> mock = mock(List.class);3 when(mock.get(0)).thenReturn("foo");4 when(mock.get(1)).thenThrow(new RuntimeException());5 when(mock.get(2)).thenThrow(new RuntimeException());6 when(mock.get(3)).thenThrow(new RuntimeException());7 when(mock.get(4)).thenThrow(new RuntimeException());8 when(mock.get(5)).thenThrow(new RuntimeException());9 when(mock.get(6)).thenThrow(new RuntimeException());10 when(mock.get(7)).thenThrow(new RuntimeException());11 when(mock.get(8)).thenThrow(new RuntimeException());12 when(mock.get(9)).thenThrow(new RuntimeException());13 when(mock.get(10)).thenThrow(new RuntimeException());14 when(mock.get(11)).thenThrow(new RuntimeException());15 when(mock.get(12)).thenThrow(new RuntimeException());16 when(mock.get(13)).thenThrow(new RuntimeException());17 when(mock.get(14)).thenThrow(new RuntimeException());18 when(mock.get(15)).thenThrow(new RuntimeException());19 when(mock.get(16)).thenThrow(new RuntimeException());20 when(mock.get(17)).thenThrow(new RuntimeException());21 when(mock.get(18)).thenThrow(new RuntimeException());22 when(mock.get(19)).thenThrow(new RuntimeException());23 when(mock.get(20)).thenThrow(new RuntimeException());24 when(mock.get(21)).thenThrow(new RuntimeException());25 when(mock.get(22)).thenThrow(new RuntimeException());26 when(mock.get(23)).thenThrow(new RuntimeException());27 when(mock.get(24)).thenThrow(new RuntimeException());28 when(mock.get(25)).thenThrow(new RuntimeException());29 when(mock.get(26)).thenThrow(new RuntimeException());30 when(mock.get(27)).thenThrow(new RuntimeException());31 when(mock.get(28)).thenThrow(new RuntimeException());32 when(mock.get(29)).thenThrow(new RuntimeException());33 when(mock.get(30)).thenThrow(new RuntimeException());34 when(mock.get(31)).thenThrow(new RuntimeException());35 when(mock.get(32)).thenThrow(new RuntimeException());36 when(mock.get(33)).thenThrow(new RuntimeException());37 when(mock.get(34)).thenThrow(new RuntimeException());38 when(mock.get(35)).thenThrow(new RuntimeException());39 when(mock.get(36)).thenThrow(new RuntimeException());40 when(mock.get(37)).thenThrow(new RuntimeException());41 when(mock.get(38)).thenThrow(new RuntimeException());42 when(mock.get(39)).thenThrow(new RuntimeException

Full Screen

Full Screen

RedundantListenerException

Using AI Code Generation

copy

Full Screen

1 public void testRedundantListenerException() {2 when(mockedList.add(any())).thenThrow(new RedundantListenerException("message"));3 assertThrows(RedundantListenerException.class, () -> {4 mockedList.add("a");5 });6 }7 public void testRedundantListenerException1() {8 when(mockedList.add(any())).thenThrow(new RedundantListenerException("message"));9 assertThrows(RedundantListenerException.class, () -> {10 mockedList.add("a");11 });12 }13 public void testRedundantListenerException2() {14 when(mockedList.add(any())).thenThrow(new RedundantListenerException("message"));15 assertThrows(RedundantListenerException.class, () -> {16 mockedList.add("a");17 });18 }19 public void testRedundantListenerException3() {20 when(mockedList.add(any())).thenThrow(new RedundantListenerException("message"));21 assertThrows(RedundantListenerException.class, () -> {22 mockedList.add("a");23 });24 }25 public void testRedundantListenerException4() {26 when(mockedList.add(any())).thenThrow(new RedundantListenerException("message"));27 assertThrows(RedundantListenerException.class, () -> {28 mockedList.add("a");29 });30 }31 public void testRedundantListenerException5() {32 when(mockedList.add(any())).thenThrow(new RedundantListenerException("message"));

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful