@Override public Object answer(InvocationOnMock invocation) throws Throwable { try { return invocation.getMock(); } finally { latch.countDown(); } } }).when(first).run();
@Override public Object answer(InvocationOnMock invocation) throws Throwable { try { return invocation.getMock(); } finally { latch.countDown(); } } }).when(second).run();
Mockito.when(reader.document(anyInt())).thenAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); Object mock = invocation.getMock(); return document(fakeIndex((int)(Integer)args[0])); } });
public Object answer(InvocationOnMock invocation) throws Throwable { Class<?> methodReturnType = invocation.getMethod().getReturnType(); Object mock = invocation.getMock(); Class<?> mockType = MockUtil.getMockHandler(mock).getMockSettings().getTypeToMock(); if (methodReturnType.isAssignableFrom(mockType)) { return invocation.getMock(); } return defaultReturn.returnValueFor(methodReturnType); }
@Override public Object answer(InvocationOnMock invocation) throws Throwable { Object mock = invocation.getMock(); if (invocation.getMethod().getReturnType().isInstance(mock)) { return mock; } else { return RETURNS_DEFAULTS.answer(invocation); } } });
public static void validateReturnValueFor(InvocationOnMock invocation, Object returnedValue) throws Throwable { InvocationInfo invocationInfo = new InvocationInfo(invocation); if (returnedValue != null && !invocationInfo.isValidReturnType(returnedValue.getClass())) { throw wrongTypeReturnedByDefaultAnswer( invocation.getMock(), invocationInfo.printMethodReturnType(), returnedValue.getClass().getSimpleName(), invocationInfo.getMethodName()); } } }
public Object answer(InvocationOnMock invocation) throws Throwable { Method mockMethod = invocation.getMethod(); try { Method delegateMethod = getDelegateMethod(mockMethod); if (!compatibleReturnTypes(mockMethod.getReturnType(), delegateMethod.getReturnType())) { throw delegatedMethodHasWrongReturnType(mockMethod, delegateMethod, invocation.getMock(), delegatedObject); } Object[] rawArguments = ((Invocation) invocation).getRawArguments(); try { delegateMethod.setAccessible(true); } catch (SecurityException ignore) { // try to invoke anyway } return delegateMethod.invoke(delegatedObject, rawArguments); } catch (NoSuchMethodException e) { throw delegatedMethodDoesNotExistOnDelegate(mockMethod, invocation.getMock(), delegatedObject); } catch (InvocationTargetException e) { // propagate the original exception from the delegate throw e.getCause(); } }
@Override @Nullable public Object answer(InvocationOnMock invocation) throws Throwable { final Section scope = ((SectionContext) invocation.getMock()).getSectionScope(); final StateUpdate stateUpdate = (StateUpdate) invocation.getArguments()[0]; stateUpdate.updateState(SectionLifecycleTestUtil.getStateContainer(scope)); return null; } })
@Override @Nullable public Object answer(InvocationOnMock invocation) throws Throwable { final Section scope = ((SectionContext) invocation.getMock()).getSectionScope(); final StateUpdate stateUpdate = (StateUpdate) invocation.getArguments()[0]; stateUpdate.updateState(SectionLifecycleTestUtil.getStateContainer(scope)); return null; } })
@Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { synchronized (handlerThreads) { handlerThreads.put( (CallRunner) invocationOnMock.getMock(), Thread.currentThread()); } countDownLatch.countDown(); return null; } };
public static MockitoException invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) { return new MockitoException(join( "Invalid argument index for the current invocation of method : ", " -> " + MockUtil.getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()", "", (willReturnLastParameter ? "Last parameter wanted" : "Wanted parameter at position " + argumentIndex) + " but " + possibleArgumentTypesOf(invocation), "The index need to be a positive number that indicates a valid position of the argument in the invocation.", "However it is possible to use the -1 value to indicates that the last argument should be returned.", "" )); }
@Override public Object answer(InvocationOnMock invocation) throws Throwable { Object mock = invocation.getMock(); if (invocation.getMethod().getReturnType().isInstance(mock)) { return mock; } else { return RETURNS_DEFAULTS.answer(invocation); } } }
public static MockitoException wrongTypeOfArgumentToReturn(InvocationOnMock invocation, String expectedType, Class<?> actualType, int argumentIndex) { return new WrongTypeOfReturnValue(join( "The argument of type '" + actualType.getSimpleName() + "' cannot be returned because the following ", "method should return the type '" + expectedType + "'", " -> " + MockUtil.getMockName(invocation.getMock()) + "." + invocation.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 " + argumentIndex + " and " + possibleArgumentTypesOf(invocation), "***", "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.", "" )); }
public Object answer(InvocationOnMock invocation) { if (isToStringMethod(invocation.getMethod())) { Object mock = invocation.getMock(); MockName name = MockUtil.getMockName(mock); if (name.isDefault()) { return "Mock for " + MockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode(); } else { return name.toString(); } } else if (isCompareToMethod(invocation.getMethod())) { //see issue 184. //mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good). //Only for compareTo() method by the Comparable interface return invocation.getMock() == invocation.getArgument(0) ? 0 : 1; } Class<?> returnType = invocation.getMethod().getReturnType(); return returnValueFor(returnType); }
public int invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) { throw new MockitoException( join("Invalid argument index for the current invocation of method : ", " -> " + new MockUtil().getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()", "", (willReturnLastParameter ? "Last parameter wanted" : "Wanted parameter at position " + argumentIndex) + " but " + possibleArgumentTypesOf(invocation), "The index need to be a positive number that indicates a valid position of the argument in the invocation.", "However it is possible to use the -1 value to indicates that the last argument should be returned.", "")); }
private Object deepStub(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable { InvocationContainerImpl container = MockUtil.getInvocationContainer(invocation.getMock()); // matches invocation for verification // TODO why don't we do container.findAnswer here? for (Stubbing stubbing : container.getStubbingsDescending()) { if (container.getInvocationForStubbing().matches(stubbing.getInvocation())) { return stubbing.answer(invocation); } } // record deep stub answer StubbedInvocationMatcher stubbing = recordDeepStubAnswer( newDeepStubMock(returnTypeGenericMetadata, invocation.getMock()), container ); // deep stubbing creates a stubbing and immediately uses it // so the stubbing is actually used by the same invocation stubbing.markStubUsed(stubbing.getInvocation()); return stubbing.answer(invocation); }
private static void mockAccept( Result mock ) { doAnswer( invocation -> { Result result = (Result) invocation.getMock(); Result.ResultVisitor visitor = invocation.getArgument( 0 ); while ( result.hasNext() ) { visitor.visit( new MapRow( result.next() ) ); } return null; } ).when( mock ) .accept( (Result.ResultVisitor<RuntimeException>) any( Result.ResultVisitor.class ) ); }
public Object answer(InvocationOnMock invocation) throws Throwable { GenericMetadataSupport returnTypeGenericMetadata = actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod()); Class<?> rawType = returnTypeGenericMetadata.rawType(); if (!mockitoCore().isTypeMockable(rawType)) { return delegate().returnValueFor(rawType); } return deepStub(invocation, returnTypeGenericMetadata); }
/** * Retrieve the expected type when it came from a primitive. If the type cannot be retrieve, return null. * * @param invocation the current invocation * @param returnType the expected return type * @return the type or null if not found */ private Class<?> findTypeFromGeneric(final InvocationOnMock invocation, final TypeVariable returnType) { // Class level final MockCreationSettings mockSettings = MockUtil.getMockHandler(invocation.getMock()).getMockSettings(); final GenericMetadataSupport returnTypeSupport = GenericMetadataSupport .inferFrom(mockSettings.getTypeToMock()) .resolveGenericReturnType(invocation.getMethod()); final Class<?> rawType = returnTypeSupport.rawType(); // Method level if (rawType == Object.class) { return findTypeFromGenericInArguments(invocation, returnType); } return rawType; }
private Object getMock(InvocationOnMock invocation) throws Throwable { InternalMockHandler<Object> handler = new MockUtil().getMockHandler(invocation.getMock()); InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer(); // matches invocation for verification for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) { if(container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) { return stubbedInvocationMatcher.answer(invocation); } } // deep stub return recordDeepStubMock(invocation, container); }