public void injectMocksOnFields(Set<Field> testClassFields, Set<Object> mocks, Object testClass) { for (Field field : testClassFields) { Object fieldInstance = null; try { fieldInstance = new FieldInitializer(testClass, field).initialize(); } catch (MockitoException e) { new Reporter().cannotInitializeForInjectMocksAnnotation(field.getName(), e); } // for each field in the class hierarchy Class<?> fieldClass = fieldInstance.getClass(); while (fieldClass != Object.class) { injectMockCandidate(fieldClass, mocks, fieldInstance); fieldClass = fieldClass.getSuperclass(); } } }
public boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) { try { SimpleArgumentResolver simpleArgumentResolver = new SimpleArgumentResolver(mockCandidates); FieldInitializationReport report = new FieldInitializer(fieldOwner, field, simpleArgumentResolver).initialize(); return report.fieldWasInitializedUsingContructorArgs(); } catch (MockitoException e) { if(e.getCause() instanceof InvocationTargetException) { Throwable realCause = e.getCause().getCause(); new Reporter().fieldInitialisationThrewException(field, realCause); } // other causes should be fine return false; } }
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) { if(mocks.size() == 1) { final Object matchingMock = mocks.iterator().next(); return new OngoingInjecter() { public Object thenInject() { try { if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) { new FieldSetter(fieldInstance, field).set(matchingMock); } } catch (RuntimeException e) { new Reporter().cannotInjectDependency(field, matchingMock, e); } return matchingMock; } }; } return new OngoingInjecter() { public Object thenInject() { return null; } }; }
@Override public void verifyInOrder(VerificationDataInOrder data) { Invocation firstUnverifiedInvocation = finder.findFirstUnverifiedInOrder(data.getOrderingContext(), data.getAllInvocations()); if (firstUnverifiedInvocation == null) { Invocation previouslyVerified = finder.findPreviousVerifiedInOrder(data.getAllInvocations(), data.getOrderingContext()); new Reporter().wantedButNotInvokedInOrder(data.getWanted(), previouslyVerified); } if (!data.getWanted().matches(firstUnverifiedInvocation)) { StringBuilder sb = new StringBuilder(); sb.append("Expected next invocation specified here: \n"); sb.append(data.getWanted().getLocation()); sb.append("\n"); sb.append("but next invocation was: \n"); sb.append(firstUnverifiedInvocation.getLocation()); sb.append("\n"); throw new MockitoAssertionError(sb.toString()); } }
private void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) { if (!lastMatchers.isEmpty()) { int recordedMatchersSize = lastMatchers.size(); int expectedMatchersSize = invocation.getArguments().length; if (expectedMatchersSize != recordedMatchersSize) { new Reporter().invalidUseOfMatchers(expectedMatchersSize, lastMatchers); } } }
public MockSettings invocationListeners(InvocationListener... listeners) { if (listeners == null || listeners.length == 0) { new Reporter().invocationListenersRequiresAtLeastOneListener(); } for (InvocationListener listener : listeners) { if (listener == null) { new Reporter().invocationListenerDoesNotAcceptNullParameters(); } this.invocationListeners.add(listener); } return this; }
public T getLastValue() { if (arguments.isEmpty()) { new Reporter().noArgumentValueWasCaptured(); return null; } else { return (T) arguments.getLast(); } }
private void validateMatchers(Invocation invocation, List<Matcher> matchers) { if (!matchers.isEmpty()) { int recordedMatchersSize = matchers.size(); int expectedMatchersSize = invocation.getArgumentsCount(); if (expectedMatchersSize != recordedMatchersSize) { new Reporter().invalidUseOfMatchers(expectedMatchersSize, recordedMatchersSize); } } }
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (new ObjectMethodsGuru().isToString(method)) { return "SmartNull returned by this unstubbed method call on a mock:\n" + invocation.toString(); } new Reporter().smartNullPointerException(invocation.toString(), location); return null; }
public void validateState() { if (!matcherStack.isEmpty()) { LocalizedMatcher lastMatcher = matcherStack.lastElement(); matcherStack.clear(); new Reporter().misplacedArgumentMatcher(lastMatcher.getLocation()); } }
void assertNoAnnotations(Class annotation, Field field, Class ... undesiredAnnotations) { for (Class u : undesiredAnnotations) { if (field.isAnnotationPresent(u)) { new Reporter().unsupportedCombinationOfAnnotations(annotation.getSimpleName(), annotation.getClass().getSimpleName()); } } }
void assertNoAnnotations(Field field, Class ... annotations) { for (Class annotation : annotations) { if (field.isAnnotationPresent(annotation)) { new Reporter().unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName()); } } }
public void validateExtraInterfaces(Class classToMock, Class ... extraInterfaces) { if (extraInterfaces == null) { return; } for (Class i : extraInterfaces) { if (classToMock == i) { new Reporter().extraInterfacesCannotContainMockedType(classToMock); } } }
public void validateMockedType(Class classToMock, Object spiedInstance) { if (classToMock == null || spiedInstance == null) { return; } if (!classToMock.equals(spiedInstance.getClass())) { new Reporter().mockedTypeIsInconsistentWithSpiedInstanceType(classToMock, spiedInstance); } }
public void verify(VerificationData data) { List<Invocation> invocations = data.getAllInvocations(); InvocationMatcher wanted = data.getWanted(); InvocationsFinder finder = new InvocationsFinder(); List<Invocation> found = finder.findInvocations(invocations, wanted); int foundSize = found.size(); if (foundSize > maxNumberOfInvocations) { new Reporter().wantedAtMostX(maxNumberOfInvocations, foundSize); } invocationMarker.markVerified(found, wanted); }
@SuppressWarnings("unchecked") public void verify(VerificationData data) { Invocation unverified = new InvocationsFinder().findFirstUnverified(data.getAllInvocations()); if (unverified != null) { new Reporter().noMoreInteractionsWanted(unverified, (List) data.getAllInvocations()); } }
public void verifyInOrder(VerificationDataInOrder data) { List<Invocation> invocations = data.getAllInvocations(); Invocation unverified = new InvocationsFinder().findFirstUnverifiedInOrder(data.getOrderingContext(), invocations); if (unverified != null) { new Reporter().noMoreInteractionsWantedInOrder(unverified); } }
void assertWantedIsVerifiable() { if (wanted == null) { return; } ObjectMethodsGuru o = new ObjectMethodsGuru(); if (o.isToString(wanted.getMethod())) { new Reporter().cannotVerifyToString(); } }
@Before public void setup() { reporter = new Reporter(); finderStub = new InvocationsFinderStub(); checker = new NumberOfInvocationsInOrderChecker(finderStub, reporter); wanted = new InvocationBuilder().toInvocationMatcher(); invocations = new LinkedList<Invocation>(asList(new InvocationBuilder().toInvocation())); }
public List<T> getLastVarargs() { if (arguments.isEmpty()) { new Reporter().noArgumentValueWasCaptured(); return null; } else { return arguments.getLast(); } }
public Object answer(InvocationOnMock currentInvocation) throws Throwable { if (new ObjectMethodsGuru().isToString(currentInvocation.getMethod())) { return "SmartNull returned by this unstubbed method call on a mock:\n" + unstubbedInvocation.toString(); } new Reporter().smartNullPointerException(unstubbedInvocation.toString(), location); return null; }
public OngoingStubbing<T> thenAnswer(Answer<?> answer) { if(!invocationContainerImpl.hasInvocationForPotentialStubbing()) { new Reporter().incorrectUseOfApi(); } invocationContainerImpl.addAnswer(answer); return new ConsecutiveStubbing<T>(invocationContainerImpl); }
public void validateIndexWithinInvocationRange(InvocationOnMock invocation) { if (!argumentPositionInRange(invocation)) { new Reporter().invalidArgumentPositionRangeAtInvocationTime(invocation, returningLastArg(), wantedArgumentPosition); } }
private void validateReturnArgIdentity(ReturnsArgumentAt returnsArgumentAt, Invocation invocation) { returnsArgumentAt.validateIndexWithinInvocationRange(invocation); MethodInfo methodInfo = new MethodInfo(invocation); if (!methodInfo.isValidReturnType(returnsArgumentAt.returnedTypeOnSignature(invocation))) { new Reporter().wrongTypeOfArgumentToReturn(invocation, methodInfo.printMethodReturnType(), returnsArgumentAt.returnedTypeOnSignature(invocation), returnsArgumentAt.wantedArgumentPosition()); } }
private void notifyMethodCall(Invocation invocation, Object returnValue) { for (InvocationListener listener : invocationListeners) { try { listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, returnValue)); } catch(Throwable listenerThrowable) { new Reporter().invocationListenerThrewException(listener, listenerThrowable); } } }
private void notifyMethodCallException(Invocation invocation, Throwable exception) { for (InvocationListener listener : invocationListeners) { try { listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, exception)); } catch(Throwable listenerThrowable) { new Reporter().invocationListenerThrewException(listener, listenerThrowable); } } }
private VerificationDataImpl createVerificationData(InvocationContainerImpl invocationContainerImpl, InvocationMatcher invocationMatcher) { if (mockSettings.isStubOnly()) { new Reporter().stubPassedToVerify(); // this throws an exception } return new VerificationDataImpl(invocationContainerImpl, invocationMatcher); }
private void assertIncorrectUseOfAdditionalMatchers(String additionalMatcherName, int count) { if(matcherStack.size() < count) { ArrayList<LocalizedMatcher> lastMatchers = new ArrayList<LocalizedMatcher>(matcherStack); matcherStack.clear(); new Reporter().incorrectUseOfAdditionalMatchers(additionalMatcherName, count, lastMatchers); } }
public void validateState() { if (!matcherStack.isEmpty()) { ArrayList lastMatchers = new ArrayList<LocalizedMatcher>(matcherStack); matcherStack.clear(); new Reporter().misplacedArgumentMatcher(lastMatchers); } }
private FieldInitializationReport initializeInjectMocksField(Field field, Object fieldOwner) { FieldInitializationReport report = null; try { report = new FieldInitializer(fieldOwner, field).initialize(); } catch (MockitoException e) { if(e.getCause() instanceof InvocationTargetException) { Throwable realCause = e.getCause().getCause(); new Reporter().fieldInitialisationThrewException(field, realCause); } new Reporter().cannotInitializeForInjectMocksAnnotation(field.getName(), e); } return report; // never null }
void assertNoAnnotations(final Field field, final Class... annotations) { for (Class annotation : annotations) { if (field.isAnnotationPresent(annotation)) { new Reporter().unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName()); } } }
void assertNoIncompatibleAnnotations(Class annotation, Field field, Class... undesiredAnnotations) { for (Class u : undesiredAnnotations) { if (field.isAnnotationPresent(u)) { new Reporter().unsupportedCombinationOfAnnotations(annotation.getSimpleName(), annotation.getClass().getSimpleName()); } } }
public void validateExtraInterfaces(Class classToMock, Collection<Class> extraInterfaces) { if (extraInterfaces == null) { return; } for (Class i : extraInterfaces) { if (classToMock == i) { new Reporter().extraInterfacesCannotContainMockedType(classToMock); } } }
public void validateDelegatedInstance(Class classToMock, Object delegatedInstance) { if (classToMock == null || delegatedInstance == null) { return; } if (delegatedInstance.getClass().isAssignableFrom(classToMock)) { new Reporter().mockedTypeIsInconsistentWithDelegatedInstanceType(classToMock, delegatedInstance); } }
public void validateSerializable(Class classToMock, boolean serializable) { // We can't catch all the errors with this piece of code // Having a **superclass that do not implements Serializable** might fail as well when serialized // Though it might prevent issues when mockito is mocking a class without superclass. if(serializable && !classToMock.isInterface() && !(Serializable.class.isAssignableFrom(classToMock)) && Constructors.noArgConstructorOf(classToMock) == null ) { new Reporter().serializableWontWorkForObjectsThatDontImplementSerializable(classToMock); } }