Best Mockito code snippet using org.mockito.internal.util.StringUtil.join
Source:Reporter.java
...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) {288 if (exc.getCause() == null) {289 return exc.getMessage();290 }291 return exc.getCause().getMessage();292 }293 public static MockitoException mockedTypeIsInconsistentWithDelegatedInstanceType(Class<?> cls, Object obj) {294 return new MockitoException(StringUtil.join("Mocked type must be the same as the type of your delegated instance.", "Mocked type must be: " + obj.getClass().getSimpleName() + ", but is: " + cls.getSimpleName(), " //correct delegate:", " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new ArrayList()<- );", " //incorrect - types don't match:", " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new HashSet()<- );"));295 }296 public static MockitoException spyAndDelegateAreMutuallyExclusive() {297 return new MockitoException(StringUtil.join("Settings should not define a spy instance and a delegated instance at the same time."));298 }299 public static MockitoException invalidArgumentRangeAtIdentityAnswerCreationTime() {300 return new MockitoException(StringUtil.join("Invalid argument index.", "The index need to be a positive number that indicates the position of the argument to return.", "However it is possible to use the -1 value to indicates that the last argument should be", "returned."));301 }302 public static MockitoException invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocationOnMock, boolean z, int i) {303 String str;304 Object[] objArr = new Object[7];305 objArr[0] = "Invalid argument index for the current invocation of method : ";306 objArr[1] = " -> " + MockUtil.getMockName(invocationOnMock.getMock()) + "." + invocationOnMock.getMethod().getName() + "()";307 objArr[2] = "";308 StringBuilder sb = new StringBuilder();309 if (z) {310 str = "Last parameter wanted";311 } else {312 str = "Wanted parameter at position " + i;313 }314 sb.append(str);315 sb.append(" but ");316 sb.append(possibleArgumentTypesOf(invocationOnMock));317 objArr[3] = sb.toString();318 objArr[4] = "The index need to be a positive number that indicates a valid position of the argument in the invocation.";319 objArr[5] = "However it is possible to use the -1 value to indicates that the last argument should be returned.";320 objArr[6] = "";321 return new MockitoException(StringUtil.join(objArr));322 }323 private static StringBuilder possibleArgumentTypesOf(InvocationOnMock invocationOnMock) {324 Class[] parameterTypes = invocationOnMock.getMethod().getParameterTypes();325 if (parameterTypes.length == 0) {326 return new StringBuilder("the method has no arguments.\n");327 }328 StringBuilder sb = new StringBuilder("the possible argument indexes for this method are :\n");329 int length = parameterTypes.length;330 for (int i = 0; i < length; i++) {331 sb.append(" [");332 sb.append(i);333 if (!invocationOnMock.getMethod().isVarArgs() || i != length - 1) {334 sb.append("] ");335 sb.append(parameterTypes[i].getSimpleName());336 sb.append(IOUtils.LINE_SEPARATOR_UNIX);337 } else {338 sb.append("+] ");339 sb.append(parameterTypes[i].getComponentType().getSimpleName());340 sb.append(" <- Vararg");341 sb.append(IOUtils.LINE_SEPARATOR_UNIX);342 }343 }344 return sb;345 }346 public static MockitoException wrongTypeOfArgumentToReturn(InvocationOnMock invocationOnMock, String str, Class<?> cls, int i) {347 return new WrongTypeOfReturnValue(StringUtil.join("The argument of type '" + cls.getSimpleName() + "' cannot be returned because the following ", "method should return the type '" + str + "'", " -> " + MockUtil.getMockName(invocationOnMock.getMock()) + "." + invocationOnMock.getMethod().getName() + "()", "", "The reason for this error can be :", "1. The wanted argument position is incorrect.", "2. The answer is used on the wrong interaction.", "", "Position of the wanted argument is " + i + " and " + possibleArgumentTypesOf(invocationOnMock), "***", "However if you're still 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.", ""));348 }349 public static MockitoException defaultAnswerDoesNotAcceptNullParameter() {350 return new MockitoException("defaultAnswer() does not accept null parameter");351 }352 public static MockitoException serializableWontWorkForObjectsThatDontImplementSerializable(Class<?> cls) {353 return new MockitoException(StringUtil.join("You are using the setting 'withSettings().serializable()' however the type you are trying to mock '" + cls.getSimpleName() + "'", "do not implement Serializable AND do not have a no-arg constructor.", "This combination is requested, otherwise you will get an 'java.io.InvalidClassException' when the mock will be serialized", "", "Also note that as requested by the Java serialization specification, the whole hierarchy need to implements Serializable,", "i.e. the top-most superclass has to implements Serializable.", ""));354 }355 public static MockitoException delegatedMethodHasWrongReturnType(Method method, Method method2, Object obj, Object obj2) {356 return new MockitoException(StringUtil.join("Methods called on delegated instance must have compatible return types with the mock.", "When calling: " + method + " on mock: " + MockUtil.getMockName(obj), "return type should be: " + method.getReturnType().getSimpleName() + ", but was: " + method2.getReturnType().getSimpleName(), "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", "(delegate instance had type: " + obj2.getClass().getSimpleName() + ")"));357 }358 public static MockitoException delegatedMethodDoesNotExistOnDelegate(Method method, Object obj, Object obj2) {359 return new MockitoException(StringUtil.join("Methods called on mock must exist in delegated instance.", "When calling: " + method + " on mock: " + MockUtil.getMockName(obj), "no such method was found.", "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", "(delegate instance had type: " + obj2.getClass().getSimpleName() + ")"));360 }361 public static MockitoException usingConstructorWithFancySerializable(SerializableMode serializableMode) {362 return new MockitoException("Mocks instantiated with constructor cannot be combined with " + serializableMode + " serialization mode.");363 }364 public static MockitoException cannotCreateTimerWithNegativeDurationTime(long j) {365 return new FriendlyReminderException(StringUtil.join("", "Don't panic! I'm just a friendly reminder!", "It is impossible for time to go backward, therefore...", "You cannot put negative value of duration: (" + j + ")", "as argument of timer methods (after(), timeout())", ""));366 }367 public static MockitoException notAnException() {368 return new MockitoException(StringUtil.join("Exception type cannot be null.", "This may happen with doThrow(Class)|thenThrow(Class) family of methods if passing null parameter."));369 }370 public static UnnecessaryStubbingException formatUnncessaryStubbingException(Class<?> cls, Collection<Invocation> collection) {371 String str;372 StringBuilder sb = new StringBuilder();373 int i = 1;374 for (Invocation location : collection) {375 sb.append("\n ");376 sb.append(i);377 sb.append(". ");378 sb.append(location.getLocation());379 i++;380 }381 if (cls != null) {382 str = "Unnecessary stubbings detected in test class: " + cls.getSimpleName();383 } else {384 str = "Unnecessary stubbings detected.";385 }386 return new UnnecessaryStubbingException(StringUtil.join(str, "Clean & maintainable test code requires zero unnecessary code.", "Following stubbings are unnecessary (click to navigate to relevant line of code):" + sb, "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class."));387 }388 public static void unncessaryStubbingException(List<Invocation> list) {389 throw formatUnncessaryStubbingException((Class<?>) null, list);390 }391 public static void potentialStubbingProblem(Invocation invocation, Collection<Invocation> collection) {392 StringBuilder sb = new StringBuilder();393 int i = 1;394 for (Invocation next : collection) {395 sb.append(" ");396 sb.append(i);397 sb.append(". ");398 sb.append(next);399 sb.append("\n ");400 sb.append(next.getLocation());401 sb.append(IOUtils.LINE_SEPARATOR_UNIX);402 i++;403 }404 sb.deleteCharAt(sb.length() - 1);405 throw new PotentialStubbingProblem(StringUtil.join("Strict stubbing argument mismatch. Please check:", " - this invocation of '" + invocation.getMethod().getName() + "' method:", " " + invocation, " " + invocation.getLocation(), " - has following stubbing(s) with different arguments:", sb, "Typically, stubbing argument mismatch indicates user mistake when writing tests.", "Mockito fails early so that you can debug potential problem easily.", "However, there are legit scenarios when this exception generates false negative signal:", " - stubbing the same method multiple times using 'given().will()' or 'when().then()' API", " Please use 'will().given()' or 'doReturn().when()' API for stubbing.", " - stubbed method is intentionally invoked with different arguments by code under test", " Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).", "For more information see javadoc for PotentialStubbingProblem class."));406 }407 public static void redundantMockitoListener(String str) {408 throw new RedundantListenerException(StringUtil.join("Problems adding Mockito listener.", "Listener of type '" + str + "' has already been added and not removed.", "It indicates that previous listener was not removed according to the API.", "When you add a listener, don't forget to remove the listener afterwards:", " Mockito.framework().removeListener(myListener);", "For more information, see the javadoc for RedundantListenerException class."));409 }410 public static void unfinishedMockingSession() {411 throw new UnfinishedMockingSessionException(StringUtil.join("Unfinished mocking session detected.", "Previous MockitoSession was not concluded with 'finishMocking()'.", "For examples of correct usage see javadoc for MockitoSession class."));412 }413}...
Source:InlineByteBuddyMockMaker.java
...61 INSTRUMENTATION = instrumentation;62 INITIALIZATION_ERROR = th;63 return;64 }65 throw new IllegalStateException(StringUtil.join("The MockMethodDispatcher class file is not locatable: " + "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher" + ".raw", "", "The class loader responsible for looking up the resource: " + cls.getClassLoader()));66 } catch (Throwable th) {67 jarOutputStream.close();68 throw th;69 }70 } else {71 throw new IllegalStateException(StringUtil.join("Byte Buddy requires retransformation for creating inline mocks. This feature is unavailable on the current VM.", "", "You cannot use this mock maker on this VM"));72 }73 } catch (ClassNotFoundException e) {74 throw new IllegalStateException(StringUtil.join("Mockito failed to inject the MockMethodDispatcher class into the bootstrap class loader", "", "It seems like your current VM does not support the instrumentation API correctly."), e);75 } catch (IOException e2) {76 try {77 throw new IllegalStateException(StringUtil.join("Mockito could not self-attach a Java agent to the current VM. This feature is required for inline mocking.", "This error occured due to an I/O error during the creation of this agent: " + e2, "", "Potentially, the current VM does not support the instrumentation API correctly"), e2);78 } catch (Throwable th2) {79 th = th2;80 }81 }82 }83 public InlineByteBuddyMockMaker() {84 if (INITIALIZATION_ERROR != null) {85 Object[] objArr = new Object[3];86 objArr[0] = "Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.)";87 objArr[1] = ToolProvider.getSystemJavaCompiler() == null ? "Are you running a JRE instead of a JDK? The inline mock maker needs to be run on a JDK.\n" : "";88 objArr[2] = Platform.describe();89 throw new MockitoInitializationException(StringUtil.join(objArr), INITIALIZATION_ERROR);90 }91 this.bytecodeGenerator = new TypeCachingBytecodeGenerator(new InlineBytecodeGenerator(INSTRUMENTATION, this.mocks), true);92 }93 public <T> T createMock(MockCreationSettings<T> mockCreationSettings, MockHandler mockHandler) {94 Class<? extends T> createMockType = createMockType(mockCreationSettings);95 try {96 T newInstance = Plugins.getInstantiatorProvider().getInstantiator(mockCreationSettings).newInstance(createMockType);97 MockMethodInterceptor mockMethodInterceptor = new MockMethodInterceptor(mockHandler, mockCreationSettings);98 this.mocks.put(newInstance, mockMethodInterceptor);99 if (newInstance instanceof MockAccess) {100 ((MockAccess) newInstance).setMockitoInterceptor(mockMethodInterceptor);101 }102 return newInstance;103 } catch (InstantiationException e) {104 throw new MockitoException("Unable to create mock instance of type '" + createMockType.getSimpleName() + "'", e);105 }106 }107 public <T> Class<? extends T> createMockType(MockCreationSettings<T> mockCreationSettings) {108 try {109 return this.bytecodeGenerator.mockClass(MockFeatures.withMockFeatures(mockCreationSettings.getTypeToMock(), mockCreationSettings.getExtraInterfaces(), mockCreationSettings.getSerializableMode(), mockCreationSettings.isStripAnnotations()));110 } catch (Exception e) {111 throw prettifyFailure(mockCreationSettings, e);112 }113 }114 private <T> RuntimeException prettifyFailure(MockCreationSettings<T> mockCreationSettings, Exception exc) {115 String str;116 Exception exc2 = exc;117 if (mockCreationSettings.getTypeToMock().isArray()) {118 throw new MockitoException(StringUtil.join("Arrays cannot be mocked: " + mockCreationSettings.getTypeToMock() + ".", ""), exc2);119 } else if (Modifier.isFinal(mockCreationSettings.getTypeToMock().getModifiers())) {120 throw new MockitoException(StringUtil.join("Mockito cannot mock this class: " + mockCreationSettings.getTypeToMock() + ".", "Can not mock final classes with the following settings :", " - explicit serialization (e.g. withSettings().serializable())", " - extra interfaces (e.g. withSettings().extraInterfaces(...))", "", "You are seeing this disclaimer because Mockito is configured to create inlined mocks.", "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.", "", "Underlying exception : " + exc2), exc2);121 } else if (!Modifier.isPrivate(mockCreationSettings.getTypeToMock().getModifiers())) {122 Object[] objArr = new Object[11];123 objArr[0] = "Mockito cannot mock this class: " + mockCreationSettings.getTypeToMock() + ".";124 objArr[1] = "";125 objArr[2] = "If you're not sure why you're getting this error, please report to the mailing list.";126 objArr[3] = "";127 if (Platform.isJava8BelowUpdate45()) {128 str = "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n";129 } else {130 str = "";131 }132 objArr[4] = Platform.warnForVM("IBM J9 VM", "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n", "Hotspot", str);133 objArr[5] = Platform.describe();134 objArr[6] = "";135 objArr[7] = "You are seeing this disclaimer because Mockito is configured to create inlined mocks.";136 objArr[8] = "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.";137 objArr[9] = "";138 objArr[10] = "Underlying exception : " + exc2;139 throw new MockitoException(StringUtil.join(objArr), exc2);140 } else {141 throw new MockitoException(StringUtil.join("Mockito cannot mock this class: " + mockCreationSettings.getTypeToMock() + ".", "Most likely it is a private class that is not visible by Mockito", "", "You are seeing this disclaimer because Mockito is configured to create inlined mocks.", "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.", ""), exc2);142 }143 }144 public MockHandler getHandler(Object obj) {145 MockMethodInterceptor mockMethodInterceptor = this.mocks.get(obj);146 if (mockMethodInterceptor == null) {147 return null;148 }149 return mockMethodInterceptor.handler;150 }151 public void resetMock(Object obj, MockHandler mockHandler, MockCreationSettings mockCreationSettings) {152 MockMethodInterceptor mockMethodInterceptor = new MockMethodInterceptor(mockHandler, mockCreationSettings);153 this.mocks.put(obj, mockMethodInterceptor);154 if (obj instanceof MockAccess) {155 ((MockAccess) obj).setMockitoInterceptor(mockMethodInterceptor);...
Source:SubclassByteBuddyMockMaker.java
...113 java.lang.String r1 = "You might experience classloading issues, please ask the mockito mailing-list."114 r4[r9] = r1115 r9 = 7116 r4[r9] = r0117 java.lang.String r9 = org.mockito.internal.util.StringUtil.join(r4)118 r3.<init>(r9, r10)119 throw r3120 */121 throw new UnsupportedOperationException("Method not decompiled: org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(org.mockito.mock.MockCreationSettings, org.mockito.invocation.MockHandler):java.lang.Object");122 }123 public <T> Class<? extends T> createMockType(MockCreationSettings<T> mockCreationSettings) {124 try {125 return this.cachingMockBytecodeGenerator.mockClass(MockFeatures.withMockFeatures(mockCreationSettings.getTypeToMock(), mockCreationSettings.getExtraInterfaces(), mockCreationSettings.getSerializableMode(), mockCreationSettings.isStripAnnotations()));126 } catch (Exception e) {127 throw prettifyFailure(mockCreationSettings, e);128 }129 }130 private static <T> T ensureMockIsAssignableToMockedType(MockCreationSettings<T> mockCreationSettings, T t) {131 return mockCreationSettings.getTypeToMock().cast(t);132 }133 private <T> RuntimeException prettifyFailure(MockCreationSettings<T> mockCreationSettings, Exception exc) {134 String str;135 if (mockCreationSettings.getTypeToMock().isArray()) {136 throw new MockitoException(StringUtil.join("Mockito cannot mock arrays: " + mockCreationSettings.getTypeToMock() + ".", ""), exc);137 } else if (!Modifier.isPrivate(mockCreationSettings.getTypeToMock().getModifiers())) {138 Object[] objArr = new Object[9];139 objArr[0] = "Mockito cannot mock this class: " + mockCreationSettings.getTypeToMock() + ".";140 objArr[1] = "";141 objArr[2] = "Mockito can only mock non-private & non-final classes.";142 objArr[3] = "If you're not sure why you're getting this error, please report to the mailing list.";143 objArr[4] = "";144 if (Platform.isJava8BelowUpdate45()) {145 str = "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n";146 } else {147 str = "";148 }149 objArr[5] = Platform.warnForVM("IBM J9 VM", "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n", "Hotspot", str);150 objArr[6] = Platform.describe();151 objArr[7] = "";152 objArr[8] = "Underlying exception : " + exc;153 throw new MockitoException(StringUtil.join(objArr), exc);154 } else {155 throw new MockitoException(StringUtil.join("Mockito cannot mock this class: " + mockCreationSettings.getTypeToMock() + ".", "Most likely it is due to mocking a private class that is not visible to Mockito", ""), exc);156 }157 }158 private static String describeClass(Class<?> cls) {159 if (cls == null) {160 return "null";161 }162 return "'" + cls.getCanonicalName() + "', loaded by classloader : '" + cls.getClassLoader() + "'";163 }164 private static String describeClass(Object obj) {165 return obj == null ? "null" : describeClass(obj.getClass());166 }167 public MockHandler getHandler(Object obj) {168 if (!(obj instanceof MockAccess)) {169 return null;170 }171 return ((MockAccess) obj).getMockitoInterceptor().getMockHandler();172 }173 public void resetMock(Object obj, MockHandler mockHandler, MockCreationSettings mockCreationSettings) {174 ((MockAccess) obj).setMockitoInterceptor(new MockMethodInterceptor(mockHandler, mockCreationSettings));175 }176 public MockMaker.TypeMockability isTypeMockable(final Class<?> cls) {177 return new MockMaker.TypeMockability() {178 public boolean mockable() {179 return !cls.isPrimitive() && !Modifier.isFinal(cls.getModifiers());180 }181 public String nonMockableReason() {182 if (mockable()) {183 return "";184 }185 if (cls.isPrimitive()) {186 return "primitive type";187 }188 if (Modifier.isFinal(cls.getModifiers())) {189 return "final class";190 }191 return StringUtil.join("not handled type");192 }193 };194 }195}...
Source:ByteBuddyCrossClassLoaderSerializationSupport.java
...47 return crossClassLoaderSerializationProxy;48 } catch (IOException e) {49 MockName mockName = MockUtil.getMockName(obj);50 String canonicalName = MockUtil.getMockSettings(obj).getTypeToMock().getCanonicalName();51 throw new MockitoSerializationIssue(StringUtil.join("The mock '" + mockName + "' of type '" + canonicalName + "'", "The Java Standard Serialization reported an '" + e.getClass().getSimpleName() + "' saying :", " " + e.getMessage()), e);52 } catch (Throwable th) {53 mockReplacementCompleted();54 this.mutex.unlock();55 throw th;56 }57 }58 private void mockReplacementCompleted() {59 this.instanceLocalCurrentlySerializingFlag = false;60 }61 private void mockReplacementStarted() {62 this.instanceLocalCurrentlySerializingFlag = true;63 }64 private boolean mockIsCurrentlyBeingReplaced() {65 return this.instanceLocalCurrentlySerializingFlag;66 }67 public static class CrossClassLoaderSerializationProxy implements Serializable {68 private static final long serialVersionUID = -7600267929109286514L;69 private final Set<Class<?>> extraInterfaces;70 private final byte[] serializedMock;71 private final Class<?> typeToMock;72 public CrossClassLoaderSerializationProxy(Object obj) throws IOException {73 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();74 MockitoMockObjectOutputStream mockitoMockObjectOutputStream = new MockitoMockObjectOutputStream(byteArrayOutputStream);75 mockitoMockObjectOutputStream.writeObject(obj);76 mockitoMockObjectOutputStream.close();77 byteArrayOutputStream.close();78 MockCreationSettings mockSettings = MockUtil.getMockSettings(obj);79 this.serializedMock = byteArrayOutputStream.toByteArray();80 this.typeToMock = mockSettings.getTypeToMock();81 this.extraInterfaces = mockSettings.getExtraInterfaces();82 }83 private Object readResolve() throws ObjectStreamException {84 try {85 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.serializedMock);86 MockitoMockObjectInputStream mockitoMockObjectInputStream = new MockitoMockObjectInputStream(byteArrayInputStream, this.typeToMock, this.extraInterfaces);87 Object readObject = mockitoMockObjectInputStream.readObject();88 byteArrayInputStream.close();89 mockitoMockObjectInputStream.close();90 return readObject;91 } catch (IOException e) {92 throw new MockitoSerializationIssue(StringUtil.join("Mockito mock cannot be deserialized to a mock of '" + this.typeToMock.getCanonicalName() + "'. The error was :", " " + e.getMessage(), "If you are unsure what is the reason of this exception, feel free to contact us on the mailing list."), e);93 } catch (ClassNotFoundException e2) {94 throw new MockitoSerializationIssue(StringUtil.join("A class couldn't be found while deserializing a Mockito mock, you should check your classpath. The error was :", " " + e2.getMessage(), "If you are still unsure what is the reason of this exception, feel free to contact us on the mailing list."), e2);95 }96 }97 }98 public static class MockitoMockObjectInputStream extends ObjectInputStream {99 private final Set<Class<?>> extraInterfaces;100 private final Class<?> typeToMock;101 public MockitoMockObjectInputStream(InputStream inputStream, Class<?> cls, Set<Class<?>> set) throws IOException {102 super(inputStream);103 this.typeToMock = cls;104 this.extraInterfaces = set;105 enableResolveObject(true);106 }107 /* access modifiers changed from: protected */108 public Class<?> resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException {109 if (notMarkedAsAMockitoMock(readObject())) {110 return super.resolveClass(objectStreamClass);111 }112 try {113 Class<?> createMockType = ((ClassCreatingMockMaker) Plugins.getMockMaker()).createMockType(new CreationSettings().setTypeToMock(this.typeToMock).setExtraInterfaces(this.extraInterfaces).setSerializableMode(SerializableMode.ACROSS_CLASSLOADERS));114 hackClassNameToMatchNewlyCreatedClass(objectStreamClass, createMockType);115 return createMockType;116 } catch (ClassCastException e) {117 throw new MockitoSerializationIssue(StringUtil.join("A Byte Buddy-generated mock cannot be deserialized into a non-Byte Buddy generated mock class", "", "The mock maker in use was: " + Plugins.getMockMaker().getClass()), e);118 }119 }120 private void hackClassNameToMatchNewlyCreatedClass(ObjectStreamClass objectStreamClass, Class<?> cls) throws ObjectStreamException {121 try {122 FieldSetter.setField(objectStreamClass, objectStreamClass.getClass().getDeclaredField("name"), cls.getCanonicalName());123 } catch (NoSuchFieldException e) {124 throw new MockitoSerializationIssue(StringUtil.join("Wow, the class 'ObjectStreamClass' in the JDK don't have the field 'name',", "this is definitely a bug in our code as it means the JDK team changed a few internal things.", "", "Please report an issue with the JDK used, a code sample and a link to download the JDK would be welcome."), e);125 }126 }127 private boolean notMarkedAsAMockitoMock(Object obj) {128 return !ByteBuddyCrossClassLoaderSerializationSupport.MOCKITO_PROXY_MARKER.equals(obj);129 }130 }131 private static class MockitoMockObjectOutputStream extends ObjectOutputStream {132 private static final String NOTHING = "";133 public MockitoMockObjectOutputStream(ByteArrayOutputStream byteArrayOutputStream) throws IOException {134 super(byteArrayOutputStream);135 }136 /* access modifiers changed from: protected */137 public void annotateClass(Class<?> cls) throws IOException {138 writeObject(mockitoProxyClassMarker(cls));...
Source:ConstructorInstantiator.java
...42 new AccessibilityChanger().enableAccess(constructor);43 return constructor.newInstance(objArr);44 }45 private InstantiationException paramsException(Class<?> cls, Exception exc) {46 return new InstantiationException(StringUtil.join("Unable to create instance of '" + cls.getSimpleName() + "'.", "Please ensure the target class has " + constructorArgsString() + " and executes cleanly."), exc);47 }48 private String constructorArgTypes() {49 int i = this.hasOuterClassInstance ? 1 : 0;50 String[] strArr = new String[(this.constructorArgs.length - i)];51 int i2 = i;52 while (true) {53 Object[] objArr = this.constructorArgs;54 if (i2 >= objArr.length) {55 return Arrays.toString(strArr);56 }57 strArr[i2 - i] = objArr[i2] == null ? null : objArr[i2].getClass().getName();58 i2++;59 }60 }61 private InstantiationException noMatchingConstructor(Class<?> cls) {62 String constructorArgsString = constructorArgsString();63 String str = this.hasOuterClassInstance ? " and provided outer instance is correct" : "";64 return new InstantiationException(StringUtil.join("Unable to create instance of '" + cls.getSimpleName() + "'.", "Please ensure that the target class has " + constructorArgsString + str + "."), (Throwable) null);65 }66 private String constructorArgsString() {67 Object[] objArr = this.constructorArgs;68 if (objArr.length == 0 || (this.hasOuterClassInstance && objArr.length == 1)) {69 return "a 0-arg constructor";70 }71 return "a constructor that matches these argument types: " + constructorArgTypes();72 }73 private InstantiationException multipleMatchingConstructors(Class<?> cls, List<Constructor<?>> list) {74 return new InstantiationException(StringUtil.join("Unable to create instance of '" + cls.getSimpleName() + "'.", "Multiple constructors could be matched to arguments of types " + constructorArgTypes() + ":", StringUtil.join("", " - ", list), "If you believe that Mockito could do a better job deciding on which constructor to use, please let us know.", "Ticket 685 contains the discussion and a workaround for ambiguous constructors using inner class.", "See https://github.com/mockito/mockito/issues/685"), (Throwable) null);75 }76 private static boolean paramsMatch(Class<?>[] clsArr, Object[] objArr) {77 if (objArr.length != clsArr.length) {78 return false;79 }80 for (int i = 0; i < objArr.length; i++) {81 if (objArr[i] == null) {82 if (clsArr[i].isPrimitive()) {83 return false;84 }85 } else if ((!clsArr[i].isPrimitive() && !clsArr[i].isInstance(objArr[i])) || (clsArr[i].isPrimitive() && !clsArr[i].equals(Primitives.primitiveTypeOf(objArr[i].getClass())))) {86 return false;87 }88 }...
Source:SubclassInjectionLoader.java
...7import org.mockito.exceptions.base.MockitoException;8import org.mockito.internal.util.Platform;9import org.mockito.internal.util.StringUtil;10class SubclassInjectionLoader implements SubclassLoader {11 private static final String ERROR_MESSAGE = StringUtil.join("The current JVM does not support any class injection mechanism.", "", "Currently, Mockito supports injection via neither by method handle lookups or using sun.misc.Unsafe", "Neither seems to be available on your current JVM.");12 private final SubclassLoader loader;13 SubclassInjectionLoader() {14 if (!Boolean.getBoolean("org.mockito.internal.noUnsafeInjection") && ClassInjector.UsingReflection.isAvailable()) {15 this.loader = new WithReflection();16 } else if (ClassInjector.UsingLookup.isAvailable()) {17 this.loader = tryLookup();18 } else {19 throw new MockitoException(StringUtil.join(ERROR_MESSAGE, "", Platform.describe()));20 }21 }22 private static SubclassLoader tryLookup() {23 try {24 Class<?> cls = Class.forName("java.lang.invoke.MethodHandles");25 Object invoke = cls.getMethod("lookup", new Class[0]).invoke((Object) null, new Object[0]);26 Method method = cls.getMethod("privateLookupIn", new Class[]{Class.class, Class.forName("java.lang.invoke.MethodHandles$Lookup")});27 return new WithLookup(invoke, method.invoke((Object) null, new Object[]{InjectionBase.class, invoke}), method);28 } catch (Exception e) {29 throw new MockitoException(StringUtil.join(ERROR_MESSAGE, "", Platform.describe()), e);30 }31 }32 private static class WithReflection implements SubclassLoader {33 public boolean isDisrespectingOpenness() {34 return true;35 }36 private WithReflection() {37 }38 public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> cls, ClassLoader classLoader, boolean z) {39 ClassLoadingStrategy.Default defaultR = ClassLoadingStrategy.Default.INJECTION;40 Class<InjectionBase> cls2 = cls;41 if (!z) {42 cls2 = InjectionBase.class;43 }44 return defaultR.with(cls2.getProtectionDomain());45 }46 }47 private static class WithLookup implements SubclassLoader {48 private final Object codegenLookup;49 private final Object lookup;50 private final Method privateLookupIn;51 public boolean isDisrespectingOpenness() {52 return false;53 }54 WithLookup(Object obj, Object obj2, Method method) {55 this.lookup = obj;56 this.codegenLookup = obj2;57 this.privateLookupIn = method;58 }59 public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> cls, ClassLoader classLoader, boolean z) {60 if (z) {61 try {62 return ClassLoadingStrategy.UsingLookup.of(this.privateLookupIn.invoke((Object) null, new Object[]{cls, this.lookup}));63 } catch (InvocationTargetException e) {64 if (e.getCause() instanceof IllegalAccessException) {65 return ClassLoadingStrategy.Default.WRAPPER.with(cls.getProtectionDomain());66 }67 throw e.getCause();68 } catch (Throwable th) {69 throw new MockitoException(StringUtil.join("The Java module system prevents Mockito from defining a mock class in the same package as " + cls, "", "To overcome this, you must open and export the mocked type to Mockito.", "Remember that you can also do so programmatically if the mocked class is defined by the same module as your test code", th));70 }71 } else if (classLoader == InjectionBase.class.getClassLoader()) {72 return ClassLoadingStrategy.UsingLookup.of(this.codegenLookup);73 } else {74 return ClassLoadingStrategy.Default.WRAPPER.with(cls.getProtectionDomain());75 }76 }77 }78 public boolean isDisrespectingOpenness() {79 return this.loader.isDisrespectingOpenness();80 }81 public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> cls, ClassLoader classLoader, boolean z) {82 return this.loader.resolveStrategy(cls, classLoader, z);83 }...
Source:StringUtil.java
...19 return text.replaceFirst(".*?\n", "");20 }21 /**22 * Joins Strings with line break character. It adds line break in front, too.23 * This makes it something like 'format' no really 'join'.24 */25 public static String join(Object... linesToBreak) {26 return join("\n", asList(linesToBreak));27 }28 /**29 * Joins Strings with EOL character30 *31 * @param start the starting String32 * @param lines collection to join33 */34 public static String join(String start, Collection<?> lines) {35 return join(start, "", lines);36 }37 /**38 * Joins Strings with EOL character39 *40 * @param start the starting String41 * @param linePrefix the prefix for each line to be joined42 * @param lines collection to join43 */44 public static String join(String start, String linePrefix, Collection<?> lines) {45 if (lines.isEmpty()) {46 return "";47 }48 StringBuilder out = new StringBuilder(start);49 for (Object line : lines) {50 out.append(linePrefix).append(line).append("\n");51 }52 return out.substring(0, out.length() - 1); // lose last EOL53 }54 public static String decamelizeMatcherName(String className) {55 if (className.length() == 0) {56 return "<custom argument matcher>";57 }58 String decamelized = decamelizeClassName(className);...
Source:StringUtilTest.java
...17 assertEquals("<Has exactly 3 elements>", StringUtil.decamelizeMatcher("HasExactly3Elements"));18 assertEquals("<custom argument matcher>", StringUtil.decamelizeMatcher(""));19 }20 @Test21 public void joins_empty_list() throws Exception {22 assertThat(StringUtil.join()).isEmpty();23 assertThat(StringUtil.join("foo", emptyList())).isEmpty();24 }25 @Test26 public void joins_single_line() throws Exception {27 assertThat(StringUtil.join("line1")).hasLineCount(2);28 }29 @Test30 public void joins_two_lines() throws Exception {31 assertThat(StringUtil.join("line1","line2")).hasLineCount(3);32 }33 @Test34 public void join_has_preceeding_linebreak() throws Exception {35 assertThat(StringUtil.join("line1")).isEqualTo("\nline1");36 }37 @Test38 public void removes_first_line() throws Exception {39 assertThat(StringUtil.removeFirstLine("line1\nline2")).isEqualTo("line2");40 }41 @Test42 public void joins_with_line_prefix() throws Exception {43 assertEquals("Hey!\n" +44 " - a\n" +45 " - b", StringUtil.join("Hey!\n", " - ", asList("a", "b")));46 }47}
join
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2public class JoinTest {3 public static void main(String[] args) {4 String[] strings = {"a", "b", "c"};5 System.out.println(StringUtil.join(strings));6 }7}8public static String join(Object[] array) {9 return join(array, ", ");10 }11public static String join(Object[] array, String separator) {12 StringBuilder builder = new StringBuilder();13 for (int i = 0; i < array.length; i++) {14 builder.append(array[i]);15 if (i < array.length - 1) {16 builder.append(separator);17 }18 }19 return builder.toString();20 }21public static String join(Object[] array, String separator, String prefix, String suffix) {22 StringBuilder builder = new StringBuilder();23 for (int i = 0; i < array.length; i++) {24 builder.append(prefix);25 builder.append(array[i]);26 builder.append(suffix);27 if (i < array.length - 1) {28 builder.append(separator);29 }30 }31 return builder.toString();32 }33public static String join(Collection<?> collection) {34 return join(collection, ", ");35 }36public static String join(Collection<?> collection, String separator) {37 return join(collection, separator, "", "");38 }39public static String join(Collection<?> collection, String separator, String prefix, String suffix) {40 return join(collection.toArray(), separator, prefix, suffix);41 }42public static String join(Object[] array, String separator, String prefix, String suffix) {43 StringBuilder builder = new StringBuilder();44 for (int i = 0; i < array.length; i++) {45 builder.append(prefix);46 builder.append(array[i]);47 builder.append(suffix);48 if (i < array.length - 1) {49 builder.append(separator);50 }51 }52 return builder.toString();53 }54public static String join(Object[] array, String separator, String prefix, String suffix) {
join
Using AI Code Generation
1package org.mockito.internal.util;2import org.mockito.internal.util.StringUtil;3public class Test {4 public static void main(String[] args) {5 String[] strings = new String[]{"a", "b", "c"};6 System.out.println(StringUtil.join(strings, ","));7 }8}
join
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2public class Test {3 public static void main(String[] args) {4 String[] str = {"a","b","c"};5 String result = StringUtil.join(str);6 System.out.println(result);7 }8}9Recommended Posts: Java | Split a string using String.split()10Java | String.split() method with regex11Java | String.split() method wi
join
Using AI Code Generation
1package org.mockito.internal.util;2import org.mockito.internal.util.StringUtil;3public class JoinTest {4 public static void main(String[] args) {5 String[] array = new String[]{"1", "2", "3"};6 String result = StringUtil.join(array, ", ");7 System.out.println(result);8 }9}
join
Using AI Code Generation
1package org.mockito.internal.util;2import org.mockito.internal.util.StringUtil;3public class Join {4 public static void main(String[] args) {5 String[] array = {"one", "two", "three", "four"};6 String result = StringUtil.join(array, ",");7 System.out.println(result);8 }9}10package org.mockito.internal.util;11import org.mockito.internal.util.StringUtil;12public class Join {13 public static void main(String[] args) {14 String[] array = {"one", "two", "three", "four"};15 String result = StringUtil.join(array, ", ", " and ");16 System.out.println(result);17 }18}
join
Using AI Code Generation
1package com.example;2import org.mockito.internal.util.StringUtil;3public class Example {4 public static void main(String[] args) {5 String[] names = { "John", "Peter", "Sam" };6 System.out.println(StringUtil.join(names));7 }8}
join
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2import java.util.Arrays;3import java.util.List;4public class JoinElements {5 public static void main(String[] args) {6 List<String> list = Arrays.asList("1", "2", "3");7 System.out.println(StringUtil.join(list));8 }9}
join
Using AI Code Generation
1package com.puppycrawl.tools.checkstyle.checks.coding;2import org.mockito.internal.util.StringUtil;3class InputIllegalTypeCheckTest {4 public void test() {5 StringUtil.join(new String[] {"test1", "test2"}, ",");6 }7}8package com.puppycrawl.tools.checkstyle.checks.coding;9import org.mockito.internal.util.StringUtil;10class InputIllegalTypeCheckTest {11 public void test() {12 StringUtil.join(new String[] {"test1", "test2"}, ",");13 }14}
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.
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!!