Best Mockito code snippet using org.mockito.internal.util.StringUtil
Source:Reporter.java
...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) {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:ImageAdaptiveMediaProcessorImplTest.java
...21import com.liferay.adaptive.media.processor.AdaptiveMedia;22import com.liferay.adaptive.media.processor.AdaptiveMediaProcessorRuntimeException;23import com.liferay.portal.kernel.repository.model.FileVersion;24import com.liferay.portal.kernel.util.MapUtil;25import com.liferay.portal.kernel.util.StringUtil;26import java.io.IOException;27import java.io.InputStream;28import java.util.Arrays;29import java.util.Collections;30import java.util.List;31import java.util.Optional;32import java.util.stream.Collectors;33import java.util.stream.Stream;34import org.junit.Assert;35import org.junit.Before;36import org.junit.Test;37import org.mockito.Mockito;38/**39 * @author Adolfo Pérez40 */41public class ImageAdaptiveMediaProcessorImplTest {42 @Before43 public void setUp() {44 _processor.setImageStorage(_imageStorage);45 _processor.setImageProcessor(_imageProcessor);46 _processor.setImageAdaptiveMediaConfigurationHelper(47 _configurationHelper);48 }49 @Test50 public void testCleanUpFileVersion() {51 Mockito.when(52 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))53 ).thenReturn(54 true55 );56 _processor.cleanUp(_fileVersion);57 Mockito.verify(58 _imageStorage59 ).delete(60 _fileVersion61 );62 }63 @Test(expected = AdaptiveMediaProcessorRuntimeException.IOException.class)64 public void testCleanUpIOException() {65 Mockito.when(66 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))67 ).thenReturn(68 true69 );70 Mockito.doThrow(71 AdaptiveMediaProcessorRuntimeException.IOException.class72 ).when(73 _imageStorage74 ).delete(75 _fileVersion76 );77 _processor.cleanUp(_fileVersion);78 }79 @Test80 public void testCleanUpWhenNotSupported() {81 Mockito.when(82 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))83 ).thenReturn(84 false85 );86 _processor.cleanUp(_fileVersion);87 Mockito.verify(88 _imageStorage, Mockito.never()89 ).delete(90 _fileVersion91 );92 }93 @Test94 public void testGetMediaAttributes() {95 ImageAdaptiveMediaConfigurationEntry configurationEntry =96 new ImageAdaptiveMediaConfigurationEntry(97 StringUtil.randomString(), StringUtil.randomString(),98 MapUtil.fromArray("height", "100", "width", "200"));99 Mockito.when(100 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(101 Mockito.any(long.class))102 ).thenReturn(103 Collections.singleton(configurationEntry)104 );105 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> stream =106 _processor.getAdaptiveMedia(107 queryBuilder -> queryBuilder.allForModel(_fileVersion));108 stream.forEach(109 adaptiveMedia -> {110 Assert.assertEquals(111 adaptiveMedia.getAttributeValue(112 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT),113 Optional.of(100));114 Assert.assertEquals(115 adaptiveMedia.getAttributeValue(116 ImageAdaptiveMediaAttribute.IMAGE_WIDTH),117 Optional.of(200));118 });119 }120 @Test(expected = IllegalArgumentException.class)121 public void testGetMediaAttributesWithNonBuilderQuery() {122 _processor.getAdaptiveMedia(123 queryBuilder ->124 new AdaptiveMediaQuery125 <FileVersion, ImageAdaptiveMediaProcessor>() {126 });127 }128 @Test(expected = IllegalArgumentException.class)129 public void testGetMediaAttributesWithNullQuery() {130 _processor.getAdaptiveMedia(queryBuilder -> null);131 }132 @Test(133 expected = AdaptiveMediaProcessorRuntimeException.InvalidConfiguration.class134 )135 public void testGetMediaConfigurationError() {136 Mockito.when(137 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))138 ).thenReturn(139 true140 );141 Mockito.when(142 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(143 Mockito.any(long.class))144 ).thenThrow(145 AdaptiveMediaProcessorRuntimeException.InvalidConfiguration.class146 );147 _processor.getAdaptiveMedia(148 queryBuilder -> queryBuilder.allForModel(_fileVersion));149 }150 @Test151 public void testGetMediaInputStream() {152 ImageAdaptiveMediaConfigurationEntry configurationEntry =153 new ImageAdaptiveMediaConfigurationEntry(154 StringUtil.randomString(), StringUtil.randomString(),155 Collections.emptyMap());156 Mockito.when(157 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(158 Mockito.any(long.class))159 ).thenReturn(160 Collections.singleton(configurationEntry)161 );162 InputStream inputStream = Mockito.mock(InputStream.class);163 Mockito.when(164 _imageStorage.getContentStream(165 _fileVersion, configurationEntry)166 ).thenReturn(167 inputStream168 );169 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> stream =170 _processor.getAdaptiveMedia(171 queryBuilder -> queryBuilder.allForModel(_fileVersion));172 stream.forEach(173 adaptiveMedia ->174 Assert.assertSame(inputStream, adaptiveMedia.getInputStream()));175 }176 @Test177 public void testGetMediaMissingAttribute() {178 ImageAdaptiveMediaConfigurationEntry configurationEntry =179 new ImageAdaptiveMediaConfigurationEntry(180 StringUtil.randomString(), StringUtil.randomString(),181 MapUtil.fromArray("height", "100"));182 Mockito.when(183 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(184 Mockito.any(long.class))185 ).thenReturn(186 Collections.singleton(configurationEntry)187 );188 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> stream =189 _processor.getAdaptiveMedia(190 queryBuilder -> queryBuilder.allForModel(_fileVersion));191 stream.forEach(192 adaptiveMedia -> {193 Assert.assertEquals(194 adaptiveMedia.getAttributeValue(195 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT),196 Optional.of(100));197 Assert.assertEquals(198 adaptiveMedia.getAttributeValue(199 ImageAdaptiveMediaAttribute.IMAGE_WIDTH),200 Optional.empty());201 });202 }203 @Test204 public void testGetMediaQueryWith100Height() {205 ImageAdaptiveMediaConfigurationEntry configurationEntry1 =206 new ImageAdaptiveMediaConfigurationEntry(207 StringUtil.randomString(), StringUtil.randomString(),208 MapUtil.fromArray("height", "100", "width", "200"));209 ImageAdaptiveMediaConfigurationEntry configurationEntry2 =210 new ImageAdaptiveMediaConfigurationEntry(211 StringUtil.randomString(), StringUtil.randomString(),212 MapUtil.fromArray("height", "200", "width", "200"));213 Mockito.when(214 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))215 ).thenReturn(216 true217 );218 Mockito.when(219 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(220 Mockito.any(long.class))221 ).thenReturn(222 Arrays.asList(configurationEntry1, configurationEntry2)223 );224 Mockito.when(225 _fileVersion.getFileName()226 ).thenReturn(227 StringUtil.randomString()228 );229 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> stream =230 _processor.getAdaptiveMedia(231 queryBuilder ->232 queryBuilder.233 forModel(_fileVersion).234 with(ImageAdaptiveMediaAttribute.IMAGE_HEIGHT, 100).235 done());236 List<AdaptiveMedia<ImageAdaptiveMediaProcessor>> adaptiveMedias =237 stream.collect(Collectors.toList());238 AdaptiveMedia<ImageAdaptiveMediaProcessor> adaptiveMedia0 =239 adaptiveMedias.get(0);240 Optional<Integer> adaptiveMedia0Optional =241 adaptiveMedia0.getAttributeValue(242 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT);243 Assert.assertEquals(100, (int)adaptiveMedia0Optional.get());244 AdaptiveMedia<ImageAdaptiveMediaProcessor> adaptiveMedia1 =245 adaptiveMedias.get(1);246 Optional<Integer> adaptiveMedia1Optional =247 adaptiveMedia1.getAttributeValue(248 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT);249 Assert.assertEquals(200, (int)adaptiveMedia1Optional.get());250 }251 @Test252 public void testGetMediaQueryWith200Height() {253 ImageAdaptiveMediaConfigurationEntry configurationEntry1 =254 new ImageAdaptiveMediaConfigurationEntry(255 StringUtil.randomString(), StringUtil.randomString(),256 MapUtil.fromArray("height", "100", "width", "200"));257 ImageAdaptiveMediaConfigurationEntry configurationEntry2 =258 new ImageAdaptiveMediaConfigurationEntry(259 StringUtil.randomString(), StringUtil.randomString(),260 MapUtil.fromArray("height", "200", "width", "200"));261 Mockito.when(262 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))263 ).thenReturn(264 true265 );266 Mockito.when(267 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(268 Mockito.any(long.class))269 ).thenReturn(270 Arrays.asList(configurationEntry1, configurationEntry2)271 );272 Mockito.when(273 _fileVersion.getFileName()274 ).thenReturn(275 StringUtil.randomString()276 );277 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> stream =278 _processor.getAdaptiveMedia(279 queryBuilder ->280 queryBuilder.281 forModel(_fileVersion).282 with(ImageAdaptiveMediaAttribute.IMAGE_HEIGHT, 200).283 done());284 List<AdaptiveMedia<ImageAdaptiveMediaProcessor>> adaptiveMedias =285 stream.collect(Collectors.toList());286 AdaptiveMedia<ImageAdaptiveMediaProcessor> adaptiveMedia0 =287 adaptiveMedias.get(0);288 Optional<Integer> adaptiveMedia0Optional =289 adaptiveMedia0.getAttributeValue(290 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT);291 Assert.assertEquals(200, (int)adaptiveMedia0Optional.get());292 AdaptiveMedia<ImageAdaptiveMediaProcessor> adaptiveMedia1 =293 adaptiveMedias.get(1);294 Optional<Integer> adaptiveMedia1Optional =295 adaptiveMedia1.getAttributeValue(296 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT);297 Assert.assertEquals(100, (int)adaptiveMedia1Optional.get());298 }299 @Test300 public void testGetMediaQueryWithNoMatchingAttributes() {301 ImageAdaptiveMediaConfigurationEntry configurationEntry1 =302 new ImageAdaptiveMediaConfigurationEntry(303 StringUtil.randomString(), StringUtil.randomString(),304 MapUtil.fromArray("height", "100"));305 ImageAdaptiveMediaConfigurationEntry configurationEntry2 =306 new ImageAdaptiveMediaConfigurationEntry(307 StringUtil.randomString(), StringUtil.randomString(),308 MapUtil.fromArray("height", "200"));309 Mockito.when(310 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))311 ).thenReturn(312 true313 );314 Mockito.when(315 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(316 Mockito.any(long.class))317 ).thenReturn(318 Arrays.asList(configurationEntry1, configurationEntry2)319 );320 Mockito.when(321 _fileVersion.getFileName()322 ).thenReturn(323 StringUtil.randomString()324 );325 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> stream =326 _processor.getAdaptiveMedia(327 queryBuilder ->328 queryBuilder.329 forModel(_fileVersion).330 with(ImageAdaptiveMediaAttribute.IMAGE_WIDTH, 100).331 done());332 List<AdaptiveMedia<ImageAdaptiveMediaProcessor>> adaptiveMedias =333 stream.collect(Collectors.toList());334 AdaptiveMedia<ImageAdaptiveMediaProcessor> adaptiveMedia0 =335 adaptiveMedias.get(0);336 Optional<Integer> adaptiveMedia0Optional =337 adaptiveMedia0.getAttributeValue(338 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT);339 Assert.assertEquals(100, (int)adaptiveMedia0Optional.get());340 AdaptiveMedia<ImageAdaptiveMediaProcessor> adaptiveMedia1 =341 adaptiveMedias.get(1);342 Optional<Integer> adaptiveMedia1Optional =343 adaptiveMedia1.getAttributeValue(344 ImageAdaptiveMediaAttribute.IMAGE_HEIGHT);345 Assert.assertEquals(200, (int)adaptiveMedia1Optional.get());346 }347 @Test348 public void testGetMediaWhenNotSupported() {349 Mockito.when(350 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))351 ).thenReturn(352 false353 );354 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> stream =355 _processor.getAdaptiveMedia(356 queryBuilder -> queryBuilder.allForModel(_fileVersion));357 Object[] adaptiveMediaArray = stream.toArray();358 Assert.assertEquals(0, adaptiveMediaArray.length);359 }360 @Test361 public void testMediaLazilyDelegatesOnStorageInputStream() {362 ImageAdaptiveMediaConfigurationEntry configurationEntry =363 new ImageAdaptiveMediaConfigurationEntry(364 StringUtil.randomString(), StringUtil.randomString(),365 MapUtil.fromArray("height", "100", "width", "200"));366 Mockito.when(367 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(368 Mockito.any(long.class))369 ).thenReturn(370 Collections.singleton(configurationEntry)371 );372 Mockito.when(373 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))374 ).thenReturn(375 true376 );377 Mockito.when(378 _fileVersion.getFileName()379 ).thenReturn(StringUtil.randomString());380 Stream<AdaptiveMedia<ImageAdaptiveMediaProcessor>> mediaStream =381 _processor.getAdaptiveMedia(382 queryBuilder -> queryBuilder.allForModel(_fileVersion));383 AdaptiveMedia<ImageAdaptiveMediaProcessor> media =384 mediaStream.findFirst().get();385 media.getInputStream();386 Mockito.verify(387 _imageStorage388 ).getContentStream(_fileVersion, configurationEntry);389 }390 @Test391 public void testProcessFileVersion() throws Exception {392 Mockito.when(393 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))394 ).thenReturn(395 true396 );397 ImageAdaptiveMediaConfigurationEntry configurationEntry =398 new ImageAdaptiveMediaConfigurationEntry(399 StringUtil.randomString(), StringUtil.randomString(),400 Collections.emptyMap());401 Mockito.when(402 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(403 Mockito.any(long.class))404 ).thenReturn(405 Collections.singleton(configurationEntry)406 );407 _processor.process(_fileVersion);408 Mockito.verify(409 _imageProcessor410 ).process(_fileVersion, configurationEntry);411 Mockito.verify(412 _imageStorage413 ).save(414 Mockito.eq(_fileVersion), Mockito.eq(configurationEntry),415 Mockito.any(InputStream.class)416 );417 }418 @Test(419 expected = AdaptiveMediaProcessorRuntimeException.InvalidConfiguration.class420 )421 public void testProcessInvalidConfigurationException() throws Exception {422 Mockito.when(423 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))424 ).thenReturn(425 true426 );427 Mockito.when(428 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(429 Mockito.any(long.class))430 ).thenThrow(431 AdaptiveMediaProcessorRuntimeException.InvalidConfiguration.class432 );433 _processor.process(_fileVersion);434 }435 @Test(expected = AdaptiveMediaProcessorRuntimeException.IOException.class)436 public void testProcessIOExceptionInImageProcessor() throws Exception {437 Mockito.when(438 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))439 ).thenReturn(440 true441 );442 ImageAdaptiveMediaConfigurationEntry configurationEntry =443 new ImageAdaptiveMediaConfigurationEntry(444 StringUtil.randomString(), StringUtil.randomString(),445 Collections.emptyMap());446 Mockito.when(447 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(448 Mockito.any(long.class))449 ).thenReturn(450 Collections.singleton(configurationEntry)451 );452 Mockito.when(453 _imageProcessor.process(_fileVersion, configurationEntry)454 ).thenThrow(455 AdaptiveMediaProcessorRuntimeException.IOException.class456 );457 _processor.process(_fileVersion);458 }459 @Test(expected = AdaptiveMediaProcessorRuntimeException.IOException.class)460 public void testProcessIOExceptionInInputStream() throws Exception {461 Mockito.when(462 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))463 ).thenReturn(464 true465 );466 ImageAdaptiveMediaConfigurationEntry configurationEntry =467 new ImageAdaptiveMediaConfigurationEntry(468 StringUtil.randomString(), StringUtil.randomString(),469 Collections.emptyMap());470 Mockito.when(471 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(472 Mockito.any(long.class))473 ).thenReturn(474 Collections.singleton(configurationEntry)475 );476 InputStream inputStream = Mockito.mock(InputStream.class);477 Mockito.when(478 _imageProcessor.process(_fileVersion, configurationEntry)479 ).thenReturn(480 inputStream481 );482 Mockito.doThrow(483 IOException.class484 ).when(485 inputStream486 ).close();487 _processor.process(_fileVersion);488 }489 @Test(expected = AdaptiveMediaProcessorRuntimeException.IOException.class)490 public void testProcessIOExceptionInStorage() throws Exception {491 Mockito.when(492 _imageProcessor.isMimeTypeSupported(Mockito.any(String.class))493 ).thenReturn(494 true495 );496 ImageAdaptiveMediaConfigurationEntry configurationEntry =497 new ImageAdaptiveMediaConfigurationEntry(498 StringUtil.randomString(), StringUtil.randomString(),499 Collections.emptyMap());500 Mockito.when(501 _configurationHelper.getImageAdaptiveMediaConfigurationEntries(502 Mockito.any(long.class))503 ).thenReturn(504 Collections.singleton(configurationEntry)505 );506 InputStream inputStream = Mockito.mock(InputStream.class);507 Mockito.when(508 _imageProcessor.process(_fileVersion, configurationEntry)509 ).thenReturn(510 inputStream511 );512 Mockito.doThrow(...
Source:InlineByteBuddyMockMaker.java
...15import org.mockito.exceptions.base.MockitoException;16import org.mockito.exceptions.base.MockitoInitializationException;17import org.mockito.internal.configuration.plugins.Plugins;18import org.mockito.internal.util.Platform;19import org.mockito.internal.util.StringUtil;20import org.mockito.internal.util.concurrent.WeakConcurrentMap;21import org.mockito.invocation.MockHandler;22import org.mockito.mock.MockCreationSettings;23import org.mockito.plugins.InlineMockMaker;24import org.mockito.plugins.MockMaker;25@Incubating26public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineMockMaker {27 private static final Throwable INITIALIZATION_ERROR;28 /* access modifiers changed from: private */29 public static final Instrumentation INSTRUMENTATION;30 private final BytecodeGenerator bytecodeGenerator;31 private final WeakConcurrentMap<Object, MockMethodInterceptor> mocks = new WeakConcurrentMap.WithInlinedExpunction();32 static {33 InputStream resourceAsStream;34 Class<InlineByteBuddyMockMaker> cls = InlineByteBuddyMockMaker.class;35 Instrumentation instrumentation = null;36 try {37 Instrumentation install = ByteBuddyAgent.install();38 if (install.isRetransformClassesSupported()) {39 File createTempFile = File.createTempFile("mockitoboot", ".jar");40 createTempFile.deleteOnExit();41 JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(createTempFile));42 try {43 resourceAsStream = cls.getClassLoader().getResourceAsStream("org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher" + ".raw");44 if (resourceAsStream != null) {45 jarOutputStream.putNextEntry(new JarEntry("org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher" + ".class"));46 byte[] bArr = new byte[1024];47 while (true) {48 int read = resourceAsStream.read(bArr);49 if (read == -1) {50 break;51 }52 jarOutputStream.write(bArr, 0, read);53 }54 resourceAsStream.close();55 jarOutputStream.closeEntry();56 jarOutputStream.close();57 install.appendToBootstrapClassLoaderSearch(new JarFile(createTempFile));58 Class.forName("org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher", false, (ClassLoader) null);59 th = null;60 instrumentation = install;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
1package org.mockito.internal.creation.bytebuddy;2import java.lang.reflect.Modifier;3import org.mockito.exceptions.base.MockitoException;4import org.mockito.internal.util.Platform;5import org.mockito.internal.util.StringUtil;6import org.mockito.invocation.MockHandler;7import org.mockito.mock.MockCreationSettings;8import org.mockito.plugins.MockMaker;9public class SubclassByteBuddyMockMaker implements ClassCreatingMockMaker {10 private final BytecodeGenerator cachingMockBytecodeGenerator;11 public SubclassByteBuddyMockMaker() {12 this(new SubclassInjectionLoader());13 }14 public SubclassByteBuddyMockMaker(SubclassLoader subclassLoader) {15 this.cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(subclassLoader), false);16 }17 /* JADX WARNING: Code restructure failed: missing block: B:10:0x0046, code lost:18 throw new org.mockito.exceptions.base.MockitoException("Unable to create mock instance of type '" + r0.getSuperclass().getSimpleName() + "'", r9);19 */20 /* JADX WARNING: Code restructure failed: missing block: B:7:0x0020, code lost:21 r10 = e;22 */23 /* JADX WARNING: Code restructure failed: missing block: B:8:0x0022, code lost:24 r9 = move-exception;25 */26 /* JADX WARNING: Failed to process nested try/catch */27 /* JADX WARNING: Removed duplicated region for block: B:8:0x0022 A[ExcHandler: InstantiationException (r9v11 'e' org.mockito.creation.instance.InstantiationException A[CUSTOM_DECLARE]), Splitter:B:1:0x000c] */28 /* Code decompiled incorrectly, please refer to instructions dump. */29 public <T> T createMock(org.mockito.mock.MockCreationSettings<T> r9, org.mockito.invocation.MockHandler r10) {30 /*31 r8 = this;32 java.lang.Class r0 = r8.createMockType(r9)33 org.mockito.plugins.InstantiatorProvider2 r1 = org.mockito.internal.configuration.plugins.Plugins.getInstantiatorProvider()34 org.mockito.creation.instance.Instantiator r1 = r1.getInstantiator(r9)35 java.lang.Object r2 = r1.newInstance(r0) // Catch:{ ClassCastException -> 0x0047, InstantiationException -> 0x0022 }36 r3 = r237 org.mockito.internal.creation.bytebuddy.MockAccess r3 = (org.mockito.internal.creation.bytebuddy.MockAccess) r3 // Catch:{ ClassCastException -> 0x0020, InstantiationException -> 0x0022 }38 org.mockito.internal.creation.bytebuddy.MockMethodInterceptor r4 = new org.mockito.internal.creation.bytebuddy.MockMethodInterceptor // Catch:{ ClassCastException -> 0x0020, InstantiationException -> 0x0022 }39 r4.<init>(r10, r9) // Catch:{ ClassCastException -> 0x0020, InstantiationException -> 0x0022 }40 r3.setMockitoInterceptor(r4) // Catch:{ ClassCastException -> 0x0020, InstantiationException -> 0x0022 }41 java.lang.Object r9 = ensureMockIsAssignableToMockedType(r9, r2) // Catch:{ ClassCastException -> 0x0020, InstantiationException -> 0x0022 }42 return r943 L_0x0020:44 r10 = move-exception45 goto L_0x004946 L_0x0022:47 r9 = move-exception48 org.mockito.exceptions.base.MockitoException r10 = new org.mockito.exceptions.base.MockitoException49 java.lang.StringBuilder r1 = new java.lang.StringBuilder50 r1.<init>()51 java.lang.String r2 = "Unable to create mock instance of type '"52 r1.append(r2)53 java.lang.Class r0 = r0.getSuperclass()54 java.lang.String r0 = r0.getSimpleName()55 r1.append(r0)56 java.lang.String r0 = "'"57 r1.append(r0)58 java.lang.String r0 = r1.toString()59 r10.<init>(r0, r9)60 throw r1061 L_0x0047:62 r10 = move-exception63 r2 = 064 L_0x0049:65 org.mockito.exceptions.base.MockitoException r3 = new org.mockito.exceptions.base.MockitoException66 r4 = 867 java.lang.Object[] r4 = new java.lang.Object[r4]68 r5 = 069 java.lang.String r6 = "ClassCastException occurred while creating the mockito mock :"70 r4[r5] = r671 r5 = 172 java.lang.StringBuilder r6 = new java.lang.StringBuilder73 r6.<init>()74 java.lang.String r7 = " class to mock : "75 r6.append(r7)76 java.lang.Class r9 = r9.getTypeToMock()77 java.lang.String r9 = describeClass((java.lang.Class<?>) r9)78 r6.append(r9)79 java.lang.String r9 = r6.toString()80 r4[r5] = r981 r9 = 282 java.lang.StringBuilder r5 = new java.lang.StringBuilder83 r5.<init>()84 java.lang.String r6 = " created class : "85 r5.append(r6)86 java.lang.String r0 = describeClass((java.lang.Class<?>) r0)87 r5.append(r0)88 java.lang.String r0 = r5.toString()89 r4[r9] = r090 r9 = 391 java.lang.StringBuilder r0 = new java.lang.StringBuilder92 r0.<init>()93 java.lang.String r5 = " proxy instance class : "94 r0.append(r5)95 java.lang.String r2 = describeClass((java.lang.Object) r2)96 r0.append(r2)97 java.lang.String r0 = r0.toString()98 r4[r9] = r099 r9 = 4100 java.lang.StringBuilder r0 = new java.lang.StringBuilder101 r0.<init>()102 java.lang.String r2 = " instance creation by : "103 r0.append(r2)104 java.lang.Class r1 = r1.getClass()105 java.lang.String r1 = r1.getSimpleName()106 r0.append(r1)107 java.lang.String r0 = r0.toString()108 r4[r9] = r0109 r9 = 5110 java.lang.String r0 = ""111 r4[r9] = r0112 r9 = 6113 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
...15import org.mockito.exceptions.base.MockitoSerializationIssue;16import org.mockito.internal.configuration.plugins.Plugins;17import org.mockito.internal.creation.settings.CreationSettings;18import org.mockito.internal.util.MockUtil;19import org.mockito.internal.util.StringUtil;20import org.mockito.internal.util.reflection.FieldSetter;21import org.mockito.mock.MockCreationSettings;22import org.mockito.mock.MockName;23import org.mockito.mock.SerializableMode;24@Incubating25class ByteBuddyCrossClassLoaderSerializationSupport implements Serializable {26 private static final String MOCKITO_PROXY_MARKER = "ByteBuddyMockitoProxyMarker";27 private static final long serialVersionUID = 7411152578314420778L;28 private boolean instanceLocalCurrentlySerializingFlag = false;29 private final Lock mutex = new ReentrantLock();30 public interface CrossClassLoaderSerializableMock {31 Object writeReplace();32 }33 ByteBuddyCrossClassLoaderSerializationSupport() {34 }35 public Object writeReplace(Object obj) throws ObjectStreamException {36 this.mutex.lock();37 try {38 if (mockIsCurrentlyBeingReplaced()) {39 mockReplacementCompleted();40 this.mutex.unlock();41 return obj;42 }43 mockReplacementStarted();44 CrossClassLoaderSerializationProxy crossClassLoaderSerializationProxy = new CrossClassLoaderSerializationProxy(obj);45 mockReplacementCompleted();46 this.mutex.unlock();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
...6import java.util.List;7import org.mockito.creation.instance.InstantiationException;8import org.mockito.creation.instance.Instantiator;9import org.mockito.internal.util.Primitives;10import org.mockito.internal.util.StringUtil;11import org.mockito.internal.util.reflection.AccessibilityChanger;12public class ConstructorInstantiator implements Instantiator {13 private final Object[] constructorArgs;14 private final boolean hasOuterClassInstance;15 public ConstructorInstantiator(boolean z, Object... objArr) {16 this.hasOuterClassInstance = z;17 this.constructorArgs = objArr;18 }19 public <T> T newInstance(Class<T> cls) {20 return withParams(cls, this.constructorArgs);21 }22 private <T> T withParams(Class<T> cls, Object... objArr) {23 LinkedList linkedList = new LinkedList();24 try {25 for (Constructor constructor : cls.getDeclaredConstructors()) {26 if (paramsMatch(constructor.getParameterTypes(), objArr)) {27 evaluateConstructor(linkedList, constructor);28 }29 }30 if (linkedList.size() == 1) {31 return invokeConstructor((Constructor) linkedList.get(0), objArr);32 }33 if (linkedList.size() == 0) {34 throw noMatchingConstructor(cls);35 }36 throw multipleMatchingConstructors(cls, linkedList);37 } catch (Exception e) {38 throw paramsException(cls, e);39 }40 }41 private static <T> T invokeConstructor(Constructor<?> constructor, Object... objArr) throws InstantiationException, IllegalAccessException, InvocationTargetException {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
...5import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;6import org.mockito.codegen.InjectionBase;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:StringUtilTest.java
...7import static java.util.Arrays.asList;8import static java.util.Collections.emptyList;9import static org.junit.Assert.assertEquals;10import static org.assertj.core.api.Assertions.assertThat;11public class StringUtilTest {12 @Test13 public void decamelizes_matcher() throws Exception {14 assertEquals("<Sentence with strong language>", StringUtil.decamelizeMatcher("SentenceWithStrongLanguage"));15 assertEquals("<W e i r d o 1>", StringUtil.decamelizeMatcher("WEIRDO1"));16 assertEquals("<_>", StringUtil.decamelizeMatcher("_"));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}
StringUtil
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2import java.util.ArrayList;3import java.util.List;4public class Test {5 public static void main(String[] args) {6 List<String> list = new ArrayList<String>();7 list.add("one");8 list.add("two");9 list.add("three");10 System.out.println(StringUtil.join(list));11 }12}13Related Posts: Java String Intern() Method14Java String indexOf() Method15Java String isEmpty() Method16Java String join() Method17Java String lastIndexOf() Method18Java String length() Method19Java String matches() Method20Java String replace() Method21Java String replaceAll() Method22Java String replaceFirst() Method23Java String split() Method24Java String startsWith() Method25Java String substring() Method26Java String toCharArray() Method27Java String toLowerCase() Method28Java String toUpperCase() Method29Java String trim() Method30Java String valueOf() Method31Java String charAt() Method32Java String codePointAt() Method33Java String codePointBefore() Method34Java String codePointCount() Method35Java String compareTo() Method36Java String compareToIgnoreCase() Method37Java String concat() Method38Java String contains() Method39Java String contentEquals() Method40Java String endsWith() Method41Java String equals() Method42Java String equalsIgnoreCase() Method43Java String format() Method44Java String getBytes() Method45Java String getChars() Method46Java String hashCode() Method47Java String intern() Method48Java String indexOf() Method49Java String isEmpty() Method50Java String join() Method51Java String lastIndexOf() Method52Java String length() Method53Java String matches() Method54Java String replace() Method55Java String replaceAll() Method56Java String replaceFirst() Method57Java String split() Method58Java String startsWith() Method59Java String substring() Method60Java String toCharArray() Method61Java String toLowerCase() Method62Java String toUpperCase() Method63Java String trim() Method64Java String valueOf() Method65Java String charAt() Method66Java String codePointAt() Method67Java String codePointBefore() Method68Java String codePointCount() Method69Java String compareTo() Method70Java String compareToIgnoreCase() Method71Java String concat() Method72Java String contains() Method73Java String contentEquals() Method74Java String endsWith() Method
StringUtil
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2public class Example {3 public static void main(String[] args)4 {5 System.out.println(StringUtil.join(", ", "a", "b", "c"));6 }7}
StringUtil
Using AI Code Generation
1import org.mockito.internal.util.*;2import java.util.*;3{4 public static void main(String args[])5 {6 Scanner sc = new Scanner(System.in);7 System.out.print("Enter the string: ");8 String s = sc.nextLine();9 System.out.println("The result is: " + StringUtil.join(new String[] {s}));10 }11}12Java | Convert String to String array using split()13Java | Convert String to String array using split() method14Java | Convert String to String array using String.split() method15Java | Convert String to String array using split() method16Java | Convert String to String array using String.split() method17Java | Convert String to String array using split() method18Java | Convert String to String array using String.split() method19Java | Convert String to String array using split() method20Java | Convert String to String array using String.split() method21Java | Convert String to String array using split() method22Java | Convert String to String array using String.split() method23Java | Convert String to String array using split() method24Java | Convert String to String array using String.split() method25Java | Convert String to String array using split() method26Java | Convert String to String array using String.split() method27Java | Convert String to String array using split() method28Java | Convert String to String array using String.split() method29Java | Convert String to String array using split() method30Java | Convert String to String array using String.split() method31Java | Convert String to String array using split() method32Java | Convert String to String array using String.split() method33Java | Convert String to String array using split() method
StringUtil
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2public class 1{3 public static void main(String args[]){4 StringUtil str = new StringUtil();5 System.out.println(str.join(new String[]{"Hello", "World"}));6 }7}8Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class)9Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, Answer)10Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockSettings)11Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockCreationSettings)12Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockName)13Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, String)14Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockName)15Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, String)16Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockCreationSettings)17Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockSettings)18Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, Answer)19Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockName)20Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, String)21Mockito - Java Testing Framework - Mocking Details - Mockito.mock(Class, MockCreationSettings)
StringUtil
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2public class 1 {3 public static void main(String[] args) {4 String str = "Hello World";5 System.out.println(StringUtil.join(" ", str, "Welcome to Java"));6 }7}
StringUtil
Using AI Code Generation
1import org.mockito.internal.util.StringUtil;2class Test {3 public static void main(String args[]) {4 System.out.println(StringUtil.join("Hello ", "World"));5 }6}
StringUtil
Using AI Code Generation
1package mypack;2import org.mockito.internal.util.StringUtil;3public class MyClass{4 public static void main(String[] args){5 StringUtil obj = new StringUtil();6 System.out.println(obj.join("Hello", "World"));7 }8}
StringUtil
Using AI Code Generation
1package com.automationrhapsody.junit;2import org.mockito.internal.util.StringUtil;3public class StringUtilTest {4 public static void main(String args[]){5 StringUtil stringUtil = new StringUtil();6 String actual = stringUtil.join(new String[]{"Hello","World"});7 System.out.println(actual);8 }9}
StringUtil
Using AI Code Generation
1package org.mockito.internal.util;2import org.mockito.internal.util.StringUtil;3class 1 {4public static void main(String[] args) {5StringUtil.removeExtraLines("This is a sample string");6}7}8Mockito verify() method9Mockito when() method10Mockito thenReturn() method11Mockito thenThrow() method12Mockito thenAnswer() method13Mockito thenCallRealMethod() method14Mockito doReturn() method15Mockito doThrow() method16Mockito doAnswer() method17Mockito doCallRealMethod() method18Mockito spy() method19Mockito reset() method20Mockito verifyNoMoreInteractions() method21Mockito verifyZeroInteractions() method22Mockito verifyNoInteractions() method23Mockito verifyNoMoreInteractions() method24Mockito verifyZeroInteractions() method25Mockito verifyNoInteractions() method26Mockito atLeast() method27Mockito atLeastOnce() method28Mockito atMost() method29Mockito times() method30Mockito only() method31Mockito never() method32Mockito inOrder() method33Mockito verify() method34Mockito when() method35Mockito thenReturn() method36Mockito thenThrow() method37Mockito thenAnswer() method38Mockito thenCallRealMethod() method39Mockito doReturn() method40Mockito doThrow() method41Mockito doAnswer() method42Mockito doCallRealMethod() method43Mockito spy() method44Mockito reset() method45Mockito verifyNoMoreInteractions() method46Mockito verifyZeroInteractions() method47Mockito verifyNoInteractions() method48Mockito verifyNoMoreInteractions() method49Mockito verifyZeroInteractions() method50Mockito verifyNoInteractions() method51Mockito atLeast() method52Mockito atLeastOnce() method53Mockito atMost() method54Mockito times() method55Mockito only() method56Mockito never() method57Mockito inOrder() method58Mockito verify() method59Mockito when() method60Mockito thenReturn() method61Mockito thenThrow() method62Mockito thenAnswer()
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!!