Best Mockito code snippet using org.mockito.exceptions.misusing.WrongTypeOfReturnValue.InjectMocksException
Source:Reporter.java
...9import org.mockito.exceptions.base.MockitoException;10import org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue;11import org.mockito.exceptions.misusing.CannotVerifyStubOnlyMock;12import org.mockito.exceptions.misusing.FriendlyReminderException;13import org.mockito.exceptions.misusing.InjectMocksException;14import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;15import org.mockito.exceptions.misusing.MissingMethodInvocationException;16import org.mockito.exceptions.misusing.NotAMockException;17import org.mockito.exceptions.misusing.NullInsteadOfMockException;18import org.mockito.exceptions.misusing.PotentialStubbingProblem;19import org.mockito.exceptions.misusing.RedundantListenerException;20import org.mockito.exceptions.misusing.UnfinishedMockingSessionException;21import org.mockito.exceptions.misusing.UnfinishedStubbingException;22import org.mockito.exceptions.misusing.UnfinishedVerificationException;23import org.mockito.exceptions.misusing.UnnecessaryStubbingException;24import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;25import org.mockito.exceptions.verification.MoreThanAllowedActualInvocations;26import org.mockito.exceptions.verification.NeverWantedButInvoked;27import org.mockito.exceptions.verification.NoInteractionsWanted;28import org.mockito.exceptions.verification.SmartNullPointerException;29import org.mockito.exceptions.verification.TooLittleActualInvocations;30import org.mockito.exceptions.verification.TooManyActualInvocations;31import org.mockito.exceptions.verification.VerificationInOrderFailure;32import org.mockito.exceptions.verification.WantedButNotInvoked;33import org.mockito.internal.debugging.LocationImpl;34import org.mockito.internal.exceptions.util.ScenarioPrinter;35import org.mockito.internal.junit.ExceptionFactory;36import org.mockito.internal.matchers.LocalizedMatcher;37import org.mockito.internal.reporting.Discrepancy;38import org.mockito.internal.reporting.Pluralizer;39import org.mockito.internal.util.MockUtil;40import org.mockito.internal.util.StringUtil;41import org.mockito.invocation.DescribedInvocation;42import org.mockito.invocation.Invocation;43import org.mockito.invocation.InvocationOnMock;44import org.mockito.invocation.Location;45import org.mockito.listeners.InvocationListener;46import org.mockito.mock.SerializableMode;47public class Reporter {48 private static final String NON_PUBLIC_PARENT = "Mocking methods declared on non-public parent classes is not supported.";49 private Reporter() {50 }51 public static MockitoException checkedExceptionInvalid(Throwable th) {52 return new MockitoException(StringUtil.join("Checked exception is invalid for this method!", "Invalid: " + th));53 }54 public static MockitoException cannotStubWithNullThrowable() {55 return new MockitoException(StringUtil.join("Cannot stub with null throwable!"));56 }57 public static MockitoException unfinishedStubbing(Location location) {58 return new UnfinishedStubbingException(StringUtil.join("Unfinished stubbing detected here:", location, "", "E.g. thenReturn() may be missing.", "Examples of correct stubbing:", " when(mock.isOk()).thenReturn(true);", " when(mock.isOk()).thenThrow(exception);", " doThrow(exception).when(mock).someVoidMethod();", "Hints:", " 1. missing thenReturn()", " 2. you are trying to stub a final method, which is not supported", " 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed", ""));59 }60 public static MockitoException incorrectUseOfApi() {61 return new MockitoException(StringUtil.join("Incorrect use of API detected here:", new LocationImpl(), "", "You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.", "Examples of correct usage:", " when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);", " when(mock.isOk()).thenReturn(true, false).thenThrow(exception);", ""));62 }63 public static MockitoException missingMethodInvocation() {64 return new MissingMethodInvocationException(StringUtil.join("when() requires an argument which has to be 'a method call on a mock'.", "For example:", " when(mock.getArticles()).thenReturn(articles);", "", "Also, this error might show up because:", "1. you stub either of: final/private/equals()/hashCode() methods.", " Those methods *cannot* be stubbed/verified.", " Mocking methods declared on non-public parent classes is not supported.", "2. inside when() you don't call method on mock but on some other object.", ""));65 }66 public static MockitoException unfinishedVerificationException(Location location) {67 return new UnfinishedVerificationException(StringUtil.join("Missing method call for verify(mock) here:", location, "", "Example of correct verification:", " verify(mock).doSomething()", "", "Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.", "Those methods *cannot* be stubbed/verified.", NON_PUBLIC_PARENT, ""));68 }69 public static MockitoException notAMockPassedToVerify(Class<?> cls) {70 return new NotAMockException(StringUtil.join("Argument passed to verify() is of type " + cls.getSimpleName() + " and is not a mock!", "Make sure you place the parenthesis correctly!", "See the examples of correct verifications:", " verify(mock).someMethod();", " verify(mock, times(10)).someMethod();", " verify(mock, atLeastOnce()).someMethod();"));71 }72 public static MockitoException nullPassedToVerify() {73 return new NullInsteadOfMockException(StringUtil.join("Argument passed to verify() should be a mock but is null!", "Examples of correct verifications:", " verify(mock).someMethod();", " verify(mock, times(10)).someMethod();", " verify(mock, atLeastOnce()).someMethod();", " not: verify(mock.someMethod());", "Also, if you use @Mock annotation don't miss initMocks()"));74 }75 public static MockitoException notAMockPassedToWhenMethod() {76 return new NotAMockException(StringUtil.join("Argument passed to when() is not a mock!", "Example of correct stubbing:", " doThrow(new RuntimeException()).when(mock).someMethod();"));77 }78 public static MockitoException nullPassedToWhenMethod() {79 return new NullInsteadOfMockException(StringUtil.join("Argument passed to when() is null!", "Example of correct stubbing:", " doThrow(new RuntimeException()).when(mock).someMethod();", "Also, if you use @Mock annotation don't miss initMocks()"));80 }81 public static MockitoException mocksHaveToBePassedToVerifyNoMoreInteractions() {82 return new MockitoException(StringUtil.join("Method requires argument(s)!", "Pass mocks that should be verified, e.g:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);", ""));83 }84 public static MockitoException notAMockPassedToVerifyNoMoreInteractions() {85 return new NotAMockException(StringUtil.join("Argument(s) passed is not a mock!", "Examples of correct verifications:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);", ""));86 }87 public static MockitoException nullPassedToVerifyNoMoreInteractions() {88 return new NullInsteadOfMockException(StringUtil.join("Argument(s) passed is null!", "Examples of correct verifications:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);"));89 }90 public static MockitoException notAMockPassedWhenCreatingInOrder() {91 return new NotAMockException(StringUtil.join("Argument(s) passed is not a mock!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);"));92 }93 public static MockitoException nullPassedWhenCreatingInOrder() {94 return new NullInsteadOfMockException(StringUtil.join("Argument(s) passed is null!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);"));95 }96 public static MockitoException mocksHaveToBePassedWhenCreatingInOrder() {97 return new MockitoException(StringUtil.join("Method requires argument(s)!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);"));98 }99 public static MockitoException inOrderRequiresFamiliarMock() {100 return new MockitoException(StringUtil.join("InOrder can only verify mocks that were passed in during creation of InOrder.", "For example:", " InOrder inOrder = inOrder(mockOne);", " inOrder.verify(mockOne).doStuff();"));101 }102 public static MockitoException invalidUseOfMatchers(int i, List<LocalizedMatcher> list) {103 return new InvalidUseOfMatchersException(StringUtil.join("Invalid use of argument matchers!", i + " matchers expected, " + list.size() + " recorded:" + locationsOf(list), "", "This exception may occur if matchers are combined with raw values:", " //incorrect:", " someMethod(anyObject(), \"raw String\");", "When using matchers, all arguments have to be provided by matchers.", "For example:", " //correct:", " someMethod(anyObject(), eq(\"String by matcher\"));", "", "For more info see javadoc for Matchers class.", ""));104 }105 public static MockitoException incorrectUseOfAdditionalMatchers(String str, int i, Collection<LocalizedMatcher> collection) {106 return new InvalidUseOfMatchersException(StringUtil.join("Invalid use of argument matchers inside additional matcher " + str + " !", new LocationImpl(), "", i + " sub matchers expected, " + collection.size() + " recorded:", locationsOf(collection), "", "This exception may occur if matchers are combined with raw values:", " //incorrect:", " someMethod(AdditionalMatchers.and(isNotNull(), \"raw String\");", "When using matchers, all arguments have to be provided by matchers.", "For example:", " //correct:", " someMethod(AdditionalMatchers.and(isNotNull(), eq(\"raw String\"));", "", "For more info see javadoc for Matchers and AdditionalMatchers classes.", ""));107 }108 public static MockitoException stubPassedToVerify(Object obj) {109 return new CannotVerifyStubOnlyMock(StringUtil.join("Argument \"" + MockUtil.getMockName(obj) + "\" passed to verify is a stubOnly() mock which cannot be verified.", "If you intend to verify invocations on this mock, don't use stubOnly() in its MockSettings."));110 }111 public static MockitoException reportNoSubMatchersFound(String str) {112 return new InvalidUseOfMatchersException(StringUtil.join("No matchers found for additional matcher " + str, new LocationImpl(), ""));113 }114 private static Object locationsOf(Collection<LocalizedMatcher> collection) {115 ArrayList arrayList = new ArrayList();116 for (LocalizedMatcher location : collection) {117 arrayList.add(location.getLocation().toString());118 }119 return StringUtil.join(arrayList.toArray());120 }121 public static AssertionError argumentsAreDifferent(String str, String str2, Location location) {122 return ExceptionFactory.createArgumentsAreDifferentException(StringUtil.join("Argument(s) are different! Wanted:", str, new LocationImpl(), "Actual invocation has different arguments:", str2, location, ""), str, str2);123 }124 public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation describedInvocation) {125 return new WantedButNotInvoked(createWantedButNotInvokedMessage(describedInvocation));126 }127 public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation describedInvocation, List<? extends DescribedInvocation> list) {128 String str;129 if (list.isEmpty()) {130 str = "Actually, there were zero interactions with this mock.\n";131 } else {132 StringBuilder sb = new StringBuilder("\nHowever, there " + Pluralizer.were_exactly_x_interactions(list.size()) + " with this mock:\n");133 for (DescribedInvocation describedInvocation2 : list) {134 sb.append(describedInvocation2.toString());135 sb.append(IOUtils.LINE_SEPARATOR_UNIX);136 sb.append(describedInvocation2.getLocation());137 sb.append("\n\n");138 }139 str = sb.toString();140 }141 String createWantedButNotInvokedMessage = createWantedButNotInvokedMessage(describedInvocation);142 return new WantedButNotInvoked(createWantedButNotInvokedMessage + str);143 }144 private static String createWantedButNotInvokedMessage(DescribedInvocation describedInvocation) {145 return StringUtil.join("Wanted but not invoked:", describedInvocation.toString(), new LocationImpl(), "");146 }147 public static MockitoAssertionError wantedButNotInvokedInOrder(DescribedInvocation describedInvocation, DescribedInvocation describedInvocation2) {148 return new VerificationInOrderFailure(StringUtil.join("Verification in order failure", "Wanted but not invoked:", describedInvocation.toString(), new LocationImpl(), "Wanted anywhere AFTER following interaction:", describedInvocation2.toString(), describedInvocation2.getLocation(), ""));149 }150 public static MockitoAssertionError tooManyActualInvocations(int i, int i2, DescribedInvocation describedInvocation, List<Location> list) {151 return new TooManyActualInvocations(createTooManyInvocationsMessage(i, i2, describedInvocation, list));152 }153 private static String createTooManyInvocationsMessage(int i, int i2, DescribedInvocation describedInvocation, List<Location> list) {154 return StringUtil.join(describedInvocation.toString(), "Wanted " + Pluralizer.pluralize(i) + ":", new LocationImpl(), "But was " + Pluralizer.pluralize(i2) + ":", createAllLocationsMessage(list), "");155 }156 public static MockitoAssertionError neverWantedButInvoked(DescribedInvocation describedInvocation, List<Location> list) {157 return new NeverWantedButInvoked(StringUtil.join(describedInvocation.toString(), "Never wanted here:", new LocationImpl(), "But invoked here:", createAllLocationsMessage(list)));158 }159 public static MockitoAssertionError tooManyActualInvocationsInOrder(int i, int i2, DescribedInvocation describedInvocation, List<Location> list) {160 String createTooManyInvocationsMessage = createTooManyInvocationsMessage(i, i2, describedInvocation, list);161 return new VerificationInOrderFailure(StringUtil.join("Verification in order failure:" + createTooManyInvocationsMessage));162 }163 private static String createAllLocationsMessage(List<Location> list) {164 if (list == null) {165 return IOUtils.LINE_SEPARATOR_UNIX;166 }167 StringBuilder sb = new StringBuilder();168 for (Location append : list) {169 sb.append(append);170 sb.append(IOUtils.LINE_SEPARATOR_UNIX);171 }172 return sb.toString();173 }174 private static String createTooLittleInvocationsMessage(Discrepancy discrepancy, DescribedInvocation describedInvocation, List<Location> list) {175 Object[] objArr = new Object[5];176 objArr[0] = describedInvocation.toString();177 StringBuilder sb = new StringBuilder();178 sb.append("Wanted ");179 sb.append(discrepancy.getPluralizedWantedCount());180 String str = ".";181 sb.append(discrepancy.getWantedCount() == 0 ? str : ":");182 objArr[1] = sb.toString();183 objArr[2] = new LocationImpl();184 StringBuilder sb2 = new StringBuilder();185 sb2.append("But was ");186 sb2.append(discrepancy.getPluralizedActualCount());187 if (discrepancy.getActualCount() != 0) {188 str = ":";189 }190 sb2.append(str);191 objArr[3] = sb2.toString();192 objArr[4] = createAllLocationsMessage(list);193 return StringUtil.join(objArr);194 }195 public static MockitoAssertionError tooLittleActualInvocations(Discrepancy discrepancy, DescribedInvocation describedInvocation, List<Location> list) {196 return new TooLittleActualInvocations(createTooLittleInvocationsMessage(discrepancy, describedInvocation, list));197 }198 public static MockitoAssertionError tooLittleActualInvocationsInOrder(Discrepancy discrepancy, DescribedInvocation describedInvocation, List<Location> list) {199 String createTooLittleInvocationsMessage = createTooLittleInvocationsMessage(discrepancy, describedInvocation, list);200 return new VerificationInOrderFailure(StringUtil.join("Verification in order failure:" + createTooLittleInvocationsMessage));201 }202 public static MockitoAssertionError noMoreInteractionsWanted(Invocation invocation, List<VerificationAwareInvocation> list) {203 String print = new ScenarioPrinter().print(list);204 return new NoInteractionsWanted(StringUtil.join("No interactions wanted here:", new LocationImpl(), "But found this interaction on mock '" + MockUtil.getMockName(invocation.getMock()) + "':", invocation.getLocation(), print));205 }206 public static MockitoAssertionError noMoreInteractionsWantedInOrder(Invocation invocation) {207 return new VerificationInOrderFailure(StringUtil.join("No interactions wanted here:", new LocationImpl(), "But found this interaction on mock '" + MockUtil.getMockName(invocation.getMock()) + "':", invocation.getLocation()));208 }209 public static MockitoException cannotMockClass(Class<?> cls, String str) {210 return new MockitoException(StringUtil.join("Cannot mock/spy " + cls.toString(), "Mockito cannot mock/spy because :", " - " + str));211 }212 public static MockitoException cannotStubVoidMethodWithAReturnValue(String str) {213 return new CannotStubVoidMethodWithReturnValue(StringUtil.join("'" + str + "' is a *void method* and it *cannot* be stubbed with a *return value*!", "Voids are usually stubbed with Throwables:", " doThrow(exception).when(mock).someVoidMethod();", "If you need to set the void method to do nothing you can use:", " doNothing().when(mock).someVoidMethod();", "For more information, check out the javadocs for Mockito.doNothing().", "***", "If you're unsure why you're getting above error read on.", "Due to the nature of the syntax above problem might occur because:", "1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.", "2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/stub final methods.", "3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", "4. Mocking methods declared on non-public parent classes is not supported.", ""));214 }215 public static MockitoException onlyVoidMethodsCanBeSetToDoNothing() {216 return new MockitoException(StringUtil.join("Only void methods can doNothing()!", "Example of correct use of doNothing():", " doNothing().", " doThrow(new RuntimeException())", " .when(mock).someVoidMethod();", "Above means:", "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called"));217 }218 public static MockitoException wrongTypeOfReturnValue(String str, String str2, String str3) {219 return new WrongTypeOfReturnValue(StringUtil.join(str2 + " cannot be returned by " + str3 + "()", str3 + "() should return " + str, "***", "If you're unsure why you're getting above error read on.", "Due to the nature of the syntax above problem might occur because:", "1. This exception *might* occur in wrongly written multi-threaded tests.", " Please refer to Mockito FAQ on limitations of concurrency testing.", "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", ""));220 }221 public static MockitoException wrongTypeReturnedByDefaultAnswer(Object obj, String str, String str2, String str3) {222 return new WrongTypeOfReturnValue(StringUtil.join("Default answer returned a result with the wrong type:", str2 + " cannot be returned by " + str3 + "()", str3 + "() should return " + str, "", "The default answer of " + MockUtil.getMockName(obj) + " that was configured on the mock is probably incorrectly implemented.", ""));223 }224 public static MoreThanAllowedActualInvocations wantedAtMostX(int i, int i2) {225 return new MoreThanAllowedActualInvocations(StringUtil.join("Wanted at most " + Pluralizer.pluralize(i) + " but was " + i2));226 }227 public static MockitoException misplacedArgumentMatcher(List<LocalizedMatcher> list) {228 return new InvalidUseOfMatchersException(StringUtil.join("Misplaced or misused argument matcher detected here:", locationsOf(list), "", "You cannot use argument matchers outside of verification or stubbing.", "Examples of correct usage of argument matchers:", " when(mock.get(anyInt())).thenReturn(null);", " doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());", " verify(mock).someMethod(contains(\"foo\"))", "", "This message may appear after an NullPointerException if the last matcher is returning an object ", "like any() but the stubbed method signature expect a primitive argument, in this case,", "use primitive alternatives.", " when(mock.get(any())); // bad use, will raise NPE", " when(mock.get(anyInt())); // correct usage use", "", "Also, this error might show up because you use argument matchers with methods that cannot be mocked.", "Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().", NON_PUBLIC_PARENT, ""));229 }230 public static MockitoException smartNullPointerException(String str, Location location) {231 return new SmartNullPointerException(StringUtil.join("You have a NullPointerException here:", new LocationImpl(), "because this method call was *not* stubbed correctly:", location, str, ""));232 }233 public static MockitoException noArgumentValueWasCaptured() {234 return new MockitoException(StringUtil.join("No argument value was captured!", "You might have forgotten to use argument.capture() in verify()...", "...or you used capture() in stubbing but stubbed method was not called.", "Be aware that it is recommended to use capture() only with verify()", "", "Examples of correct argument capturing:", " ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);", " verify(mock).doSomething(argument.capture());", " assertEquals(\"John\", argument.getValue().getName());", ""));235 }236 public static MockitoException extraInterfacesDoesNotAcceptNullParameters() {237 return new MockitoException(StringUtil.join("extraInterfaces() does not accept null parameters."));238 }239 public static MockitoException extraInterfacesAcceptsOnlyInterfaces(Class<?> cls) {240 return new MockitoException(StringUtil.join("extraInterfaces() accepts only interfaces.", "You passed following type: " + cls.getSimpleName() + " which is not an interface."));241 }242 public static MockitoException extraInterfacesCannotContainMockedType(Class<?> cls) {243 return new MockitoException(StringUtil.join("extraInterfaces() does not accept the same type as the mocked type.", "You mocked following type: " + cls.getSimpleName(), "and you passed the same very interface to the extraInterfaces()"));244 }245 public static MockitoException extraInterfacesRequiresAtLeastOneInterface() {246 return new MockitoException(StringUtil.join("extraInterfaces() requires at least one interface."));247 }248 public static MockitoException mockedTypeIsInconsistentWithSpiedInstanceType(Class<?> cls, Object obj) {249 return new MockitoException(StringUtil.join("Mocked type must be the same as the type of your spied instance.", "Mocked type must be: " + obj.getClass().getSimpleName() + ", but is: " + cls.getSimpleName(), " //correct spying:", " spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );", " //incorrect - types don't match:", " spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );"));250 }251 public static MockitoException cannotCallAbstractRealMethod() {252 return new MockitoException(StringUtil.join("Cannot call abstract real method on java object!", "Calling real methods is only possible when mocking non abstract method.", " //correct example:", " when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();"));253 }254 public static MockitoException cannotVerifyToString() {255 return new MockitoException(StringUtil.join("Mockito cannot verify toString()", "toString() is too often used behind of scenes (i.e. during String concatenation, in IDE debugging views). Verifying it may give inconsistent or hard to understand results. Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)", "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases."));256 }257 public static MockitoException moreThanOneAnnotationNotAllowed(String str) {258 return new MockitoException("You cannot have more than one Mockito annotation on a field!\nThe field '" + str + "' has multiple Mockito annotations.\nFor info how to use annotations see examples in javadoc for MockitoAnnotations class.");259 }260 public static MockitoException unsupportedCombinationOfAnnotations(String str, String str2) {261 return new MockitoException("This combination of annotations is not permitted on a single field:\n@" + str + " and @" + str2);262 }263 public static MockitoException cannotInitializeForSpyAnnotation(String str, Exception exc) {264 return new MockitoException(StringUtil.join("Cannot instantiate a @Spy for '" + str + "' field.", "You haven't provided the instance for spying at field declaration so I tried to construct the instance.", "However, I failed because: " + exc.getMessage(), "Examples of correct usage of @Spy:", " @Spy List mock = new LinkedList();", " @Spy Foo foo; //only if Foo has parameterless constructor", " //also, don't forget about MockitoAnnotations.initMocks();", ""), exc);265 }266 public static MockitoException cannotInitializeForInjectMocksAnnotation(String str, String str2) {267 return new MockitoException(StringUtil.join("Cannot instantiate @InjectMocks field named '" + str + "'! Cause: " + str2, "You haven't provided the instance at field declaration so I tried to construct the instance.", "Examples of correct usage of @InjectMocks:", " @InjectMocks Service service = new Service();", " @InjectMocks Service service;", " //and... don't forget about some @Mocks for injection :)", ""));268 }269 public static MockitoException atMostAndNeverShouldNotBeUsedWithTimeout() {270 return new FriendlyReminderException(StringUtil.join("", "Don't panic! I'm just a friendly reminder!", "timeout() should not be used with atMost() or never() because...", "...it does not make much sense - the test would have passed immediately in concurrency", "We kept this method only to avoid compilation errors when upgrading Mockito.", "In future release we will remove timeout(x).atMost(y) from the API.", "If you want to find out more please refer to issue 235", ""));271 }272 public static MockitoException fieldInitialisationThrewException(Field field, Throwable th) {273 return new InjectMocksException(StringUtil.join("Cannot instantiate @InjectMocks field named '" + field.getName() + "' of type '" + field.getType() + "'.", "You haven't provided the instance at field declaration so I tried to construct the instance.", "However the constructor or the initialization block threw an exception : " + th.getMessage(), ""), th);274 }275 public static MockitoException methodDoesNotAcceptParameter(String str, String str2) {276 return new MockitoException(str + "() does not accept " + str2 + " See the Javadoc.");277 }278 public static MockitoException requiresAtLeastOneListener(String str) {279 return new MockitoException(str + "() requires at least one listener");280 }281 public static MockitoException invocationListenerThrewException(InvocationListener invocationListener, Throwable th) {282 return new MockitoException(StringUtil.join("The invocation listener with type " + invocationListener.getClass().getName(), "threw an exception : " + th.getClass().getName() + th.getMessage()), th);283 }284 public static MockitoException cannotInjectDependency(Field field, Object obj, Exception exc) {285 return new MockitoException(StringUtil.join("Mockito couldn't inject mock dependency '" + MockUtil.getMockName(obj) + "' on field ", "'" + field + "'", "whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.", "Also I failed because: " + exceptionCauseMessageIfAvailable(exc), ""), exc);286 }287 private static String exceptionCauseMessageIfAvailable(Exception exc) {...InjectMocksException
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.InjectMocks;4import org.mockito.Mock;5import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;6import org.mockito.runners.MockitoJUnitRunner;7import org.mockito.stubbing.Answer;8import static org.junit.Assert.*;9import static org.mockito.Mockito.*;10@RunWith(MockitoJUnitRunner.class)11public class InjectMocksExceptionTest {12 private Answer<String> answer;13 private InjectMocksException injectMocksException;14 @Test(expected = WrongTypeOfReturnValue.class)15 public void testInjectMocksException() {16 when(answer.answer(null)).thenReturn("answer");17 injectMocksException.answer();18 }19}20You have a spy on InjectMocksException class and try to return a value from answer() method. 21However, answer() is not a mock method. 22at org.mockito.exceptions.misusing.WrongTypeOfReturnValue.create(WrongTypeOfReturnValue.java:21)23at org.mockito.internal.stubbing.answers.ReturnsMocksHandler.handle(ReturnsMocksHandler.java:24)24at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:95)25at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)26at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)27at org.mockito.internal.creation.cglib.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:59)28at com.baeldung.mockito.InjectMocksException$$EnhancerByMockitoWithCGLIB$$b8e1d1e.answer(<generated>)29at com.baeldung.mockito.InjectMocksExceptionTest.testInjectMocksException(InjectMocksExceptionTest.java:25)InjectMocksException
Using AI Code Generation
1 public void testInjectMocksException() {2 WrongTypeOfReturnValue wrongTypeOfReturnValue = new WrongTypeOfReturnValue();3 wrongTypeOfReturnValue.injectMocksException();4 }5}6 public abstract java.lang.String org.mockito.exceptions.misusing.WrongTypeOfReturnValue.giveMeSomeString()7 2. return primitive value (e.g. zero) or wrapper class (e.g. Boolean.FALSE) if that's what the method expect8 3. return Mockito.mock() if the method return type is an interface9 4. return Mockito.mock() if the method return type is a class10 5. if you don't care what the method returns use Mockito.doReturn() or Mockito.doThrow() for stubbing11 at org.mockito.exceptions.misusing.WrongTypeOfReturnValue.giveMeSomeString(WrongTypeOfReturnValue.java:10)12 at org.mockito.exceptions.misusing.WrongTypeOfReturnValue.injectMocksException(WrongTypeOfReturnValue.java:16)13 at com.baeldung.mockito.exceptions.WrongTypeOfReturnValueUnitTest.testInjectMocksException(WrongTypeOfReturnValueUnitTest.java:24)14 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)15 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)16 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)17 at java.lang.reflect.Method.invoke(Method.java:498)18 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)19 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)20 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)21 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)22 at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)23 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)24 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)InjectMocksException
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.InjectMocks;4import org.mockito.Mock;5import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;6import org.mockito.junit.MockitoJUnitRunner;7import java.util.List;8import static org.junit.Assert.assertEquals;9import static org.mockito.Mockito.when;10@RunWith(MockitoJUnitRunner.class)11public class WrongTypeOfReturnValueTest {12 private List<String> mockedList;13 private WrongTypeOfReturnValue wrongTypeOfReturnValue;14 public void test() {15 when(mockedList.get(0)).thenReturn("first");16 assertEquals("first", mockedList.get(0));17 try {18 when(mockedList.get(1)).thenReturn(1);19 } catch (WrongTypeOfReturnValue e) {20 assertEquals("Return type of method 'get' has to be String, but is int.", e.getMessage());21 }22 }23}24 at org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues.validateType(ReturnsMoreEmptyValues.java:55)25 at org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues.answer(ReturnsMoreEmptyValues.java:44)26 at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91)27 at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)28 at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)29 at org.mockito.internal.creation.cglib.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:59)30 at java.util.List$$EnhancerByMockitoWithCGLIB$$d0a3a3a3.get()31 at WrongTypeOfReturnValueTest.test(WrongTypeOfReturnValueTest.java:30)InjectMocksException
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.InjectMocks;4import org.mockito.Mock;5import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;6import org.mockito.junit.MockitoJUnitRunner;7@RunWith(MockitoJUnitRunner.class)8public class InjectMocksExceptionTest {9 private Dependency dependency;10 private ClassUnderTest classUnderTest;11 @Test(expected = WrongTypeOfReturnValue.class)12 public void testInjectMocksException() {13 classUnderTest.methodReturningDependency();14 }15}16Return value of method methodReturningDependency() of class ClassUnderTest is not of the same type as the injected field dependencyLearn 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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
