下面列出了怎么用org.mockito.internal.util.MockUtil的API类实例代码及写法,或者点击链接到github查看源代码。
private static final LdapConnection verify( LdapConnection connection, VerificationMode mode )
{
if ( MockUtil.isMock( connection ) )
{
return org.mockito.Mockito.verify( connection, mode );
}
else
{
if ( connection instanceof Wrapper )
{
@SuppressWarnings("unchecked")
LdapConnection unwrapped = ( ( Wrapper<LdapConnection> ) connection ).wrapped();
return verify( unwrapped, mode );
}
}
throw new NotAMockException( "connection is not a mock, nor a wrapper for a connection that is one" );
}
@Before
public void setup() {
WXEnvironment.sApplication = RuntimeEnvironment.application;
WXSDKManager wxsdkManager = WXSDKManager.getInstance();
if (!new MockUtil().isSpy(wxsdkManager)) {
WXSDKManager spy = Mockito.spy(wxsdkManager);
WXSDKManagerTest.setInstance(spy);
Mockito.when(spy.getIWXHttpAdapter()).thenReturn(new IWXHttpAdapter() {
@Override
public void sendRequest(WXRequest request, OnHttpListener listener) {
//do nothing.
}
});
}
adapter = new DefaultUriAdapter();
instance = WXSDKInstanceTest.createInstance();
}
@Before
public void setup() {
WXEnvironment.sApplication = RuntimeEnvironment.application;
WXSDKManager wxsdkManager = WXSDKManager.getInstance();
if (!new MockUtil().isSpy(wxsdkManager)) {
WXSDKManager spy = Mockito.spy(wxsdkManager);
WXSDKManagerTest.setInstance(spy);
Mockito.when(spy.getIWXHttpAdapter()).thenReturn(new IWXHttpAdapter() {
@Override
public void sendRequest(WXRequest request, OnHttpListener listener) {
//do nothing.
}
});
}
adapter = new DefaultUriAdapter();
instance = WXSDKInstanceTest.createInstance();
}
public Object answer(InvocationOnMock invocation) {
if (methodsGuru.isToString(invocation.getMethod())) {
Object mock = invocation.getMock();
MockName name = new MockUtil().getMockName(mock);
if (name.isSurrogate()) {
return "Mock for " + ClassNameFinder.classNameForMock(mock) + ", hashCode: " + mock.hashCode();
} else {
return name.toString();
}
} else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {
//see issue 184.
//mocks by default should not return 0 for compareTo because they are not the same. Hence we return 1 (anything but 0 is good).
//Only for compareTo() method by the Comparable interface
return 1;
}
Class<?> returnType = invocation.getMethod().getReturnType();
return returnValueFor(returnType);
}
public void wrongTypeOfArgumentToReturn(InvocationOnMock invocation, String expectedType, Class actualType, int argumentIndex) {
throw new WrongTypeOfReturnValue(join(
"The argument of type '" + actualType.getSimpleName() + "' cannot be returned because the following ",
"method should return the type '" + expectedType + "'",
" -> " + new 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.",
""
));
}
/**
* Verify the same invocations have been applied to two mocks. This is generally not
* the preferred way test with mockito and should be avoided if possible.
* @param expected the mock containing expected invocations
* @param actual the mock containing actual invocations
* @param argumentAdapters adapters that can be used to change argument values before they are compared
*/
public static <T> void verifySameInvocations(T expected, T actual, InvocationArgumentsAdapter... argumentAdapters) {
List<Invocation> expectedInvocations =
((InvocationContainerImpl) MockUtil.getMockHandler(expected).getInvocationContainer()).getInvocations();
List<Invocation> actualInvocations =
((InvocationContainerImpl) MockUtil.getMockHandler(actual).getInvocationContainer()).getInvocations();
verifySameInvocations(expectedInvocations, actualInvocations, argumentAdapters);
}
/**
* Verify the same invocations have been applied to two mocks. This is generally not
* the preferred way test with mockito and should be avoided if possible.
* @param expected the mock containing expected invocations
* @param actual the mock containing actual invocations
* @param argumentAdapters adapters that can be used to change argument values before they are compared
*/
public static <T> void verifySameInvocations(T expected, T actual, InvocationArgumentsAdapter... argumentAdapters) {
List<Invocation> expectedInvocations =
((InvocationContainerImpl) MockUtil.getMockHandler(expected).getInvocationContainer()).getInvocations();
List<Invocation> actualInvocations =
((InvocationContainerImpl) MockUtil.getMockHandler(actual).getInvocationContainer()).getInvocations();
verifySameInvocations(expectedInvocations, actualInvocations, argumentAdapters);
}
/**
* gets all invocations from mocks. Invocations are ordered earlier first.
*
* @param mocks mocks
* @return invocations
*/
public List<Invocation> find(List<?> mocks) {
Set<Invocation> invocationsInOrder = new TreeSet<Invocation>(new SequenceNumberComparator());
for (Object mock : mocks) {
MockHandlerInterface<Object> handler = new MockUtil().getMockHandler(mock);
List<Invocation> fromSingleMock = handler.getInvocationContainer().getInvocations();
invocationsInOrder.addAll(fromSingleMock);
}
return new LinkedList<Invocation>(invocationsInOrder);
}
/**
* Finds all unused stubs for given mocks
*
* @param mocks
*/
public List<Invocation> find(List<?> mocks) {
List<Invocation> unused = new LinkedList<Invocation>();
for (Object mock : mocks) {
MockHandlerInterface<Object> handler = new MockUtil().getMockHandler(mock);
List<StubbedInvocationMatcher> fromSingleMock = handler.getInvocationContainer().getStubbedInvocations();
for(StubbedInvocationMatcher s : fromSingleMock) {
if (!s.wasUsed()) {
unused.add(s.getInvocation());
}
}
}
return unused;
}
public <T> T when(T mock) {
MockUtil mockUtil = new MockUtil();
if (mock == null) {
reporter.nullPassedToWhenMethod();
} else {
if (!mockUtil.isMock(mock)) {
reporter.notAMockPassedToWhenMethod();
}
}
mockUtil.getMockHandler(mock).setAnswersForStubbing(answers);
return mock;
}
public Object answer(InvocationOnMock invocation) throws Throwable {
if (new MockUtil().isMock(throwable)) {
throw throwable;
}
Throwable t = throwable.fillInStackTrace();
filter.filter(t);
throw t;
}
public void cannotInjectDependency(Field field, Object matchingMock, Exception details) {
throw new MockitoException(join(
"Mockito couldn't inject mock dependency '" + new MockUtil().getMockName(matchingMock) + "' on field ",
"'" + field + "'",
"whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.",
"Also I failed because: " + details.getCause().getMessage(),
""
), details);
}
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.",
""));
}
public String print(List<Matcher> matchers, Invocation invocation) {
MatchersPrinter matchersPrinter = new MatchersPrinter();
String qualifiedName = new MockUtil().getMockName(invocation.getMock()) + "." + invocation.getMethod().getName();
String invocationString = qualifiedName + matchersPrinter.getArgumentsLine(matchers, this);
if (isMultiline() || (!matchers.isEmpty() && invocationString.length() > MAX_LINE_LENGTH)) {
return qualifiedName + matchersPrinter.getArgumentsBlock(matchers, this);
} else {
return invocationString;
}
}
public Object[] ignoreStubs(Object... mocks) {
for (Object m : mocks) {
InvocationContainer invocationContainer = new MockUtil().getMockHandler(m).getInvocationContainer();
List<Invocation> ins = invocationContainer.getInvocations();
for (Invocation in : ins) {
if (in.stubInfo() != null) {
in.ignoreForVerification();
}
}
}
return mocks;
}
/**
* Finds all unused stubs for given mocks
*
* @param mocks
*/
public List<Invocation> find(List<?> mocks) {
List<Invocation> unused = new LinkedList<Invocation>();
for (Object mock : mocks) {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(mock);
List<StubbedInvocationMatcher> fromSingleMock = handler.getInvocationContainer().getStubbedInvocations();
for(StubbedInvocationMatcher s : fromSingleMock) {
if (!s.wasUsed()) {
unused.add(s.getInvocation());
}
}
}
return unused;
}
/**
* gets all invocations from mocks. Invocations are ordered earlier first.
*
* @param mocks mocks
* @return invocations
*/
public List<Invocation> find(List<?> mocks) {
Set<Invocation> invocationsInOrder = new TreeSet<Invocation>(new SequenceNumberComparator());
for (Object mock : mocks) {
InternalMockHandler<Object> handler = new MockUtil().getMockHandler(mock);
List<Invocation> fromSingleMock = handler.getInvocationContainer().getInvocations();
invocationsInOrder.addAll(fromSingleMock);
}
return new LinkedList<Invocation>(invocationsInOrder);
}
private Object deepStub(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) 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);
}
}
// record deep stub answer
return recordDeepStubAnswer(newDeepStubMock(returnTypeGenericMetadata), container);
}
public <T> T when(T mock) {
MockUtil mockUtil = new MockUtil();
if (mock == null) {
reporter.nullPassedToWhenMethod();
} else {
if (!mockUtil.isMock(mock)) {
reporter.notAMockPassedToWhenMethod();
}
}
mockUtil.getMockHandler(mock).setAnswersForStubbing(answers);
return mock;
}
public Object answer(InvocationOnMock invocation) throws Throwable {
if (new MockUtil().isMock(throwable)) {
throw throwable;
}
Throwable t = throwable.fillInStackTrace();
filter.filter(t);
throw t;
}
@Override
protected boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) {
FieldReader fieldReader = new FieldReader(fieldOwner, field);
// TODO refoctor : code duplicated in SpyAnnotationEngine
if(!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) {
try {
Object instance = fieldReader.read();
if (new MockUtil().isMock(instance)) {
// A. instance has been spied earlier
// B. protect against multiple use of MockitoAnnotations.initMocks()
Mockito.reset(instance);
} else {
new FieldSetter(fieldOwner, field).set(
Mockito.mock(instance.getClass(), withSettings()
.spiedInstance(instance)
.defaultAnswer(Mockito.CALLS_REAL_METHODS)
.name(field.getName()))
);
}
} catch (Exception e) {
throw new MockitoException("Problems initiating spied field " + field.getName(), e);
}
}
return false;
}
/**
* Creates the wrapper that be used in the serialization stream.
*
* <p>Immediately serializes the Mockito mock using specifically crafted {@link MockitoMockObjectOutputStream},
* in a byte array.</p>
*
* @param mockitoMock The Mockito mock to serialize.
* @throws IOException
*/
public AcrossJVMMockSerializationProxy(Object mockitoMock) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new MockitoMockObjectOutputStream(out);
objectOutputStream.writeObject(mockitoMock);
objectOutputStream.close();
out.close();
MockCreationSettings mockSettings = new MockUtil().getMockSettings(mockitoMock);
this.serializedMock = out.toByteArray();
this.typeToMock = mockSettings.getTypeToMock();
this.extraInterfaces = mockSettings.getExtraInterfaces();
}
@Test
public void shouldCreateSampleValueOfAnyObject() {
Object sample = new ToStringChecker<Object>(Object.class)
.createSampleValueOfType(Object.class);
MockUtil.isMock(sample);
assertThat(sample.getClass().getSuperclass()).isEqualTo(Object.class);
}
/**
* This is a best effort automatic test for method forwarding between a delegate and its wrapper, where the wrapper
* class is a subtype of the delegate. Methods can be remapped in case that the implementation does not call the
* original method. Remapping to null skips the method. This ignores methods that are inherited from Object.
*
* @param delegateClass the class for the delegate.
* @param wrapperFactory factory that produces a wrapper from a delegate.
* @param delegateObjectSupplier supplier for the delegate object passed to the wrapper factory.
* @param skipMethodSet set of methods to ignore.
* @param <D> type of the delegate
* @param <W> type of the wrapper
* @param <I> type of the object created as delegate, is a subtype of D.
*/
public static <D, W, I extends D> void testMethodForwarding(
Class<D> delegateClass,
Function<I, W> wrapperFactory,
Supplier<I> delegateObjectSupplier,
Set<Method> skipMethodSet) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Preconditions.checkNotNull(delegateClass);
Preconditions.checkNotNull(wrapperFactory);
Preconditions.checkNotNull(skipMethodSet);
I delegate = delegateObjectSupplier.get();
//check if we need to wrap the delegate object as a spy, or if it is already testable with Mockito.
if (!MockUtil.isSpy(delegate) || !MockUtil.isMock(delegate)) {
delegate = spy(delegate);
}
W wrapper = wrapperFactory.apply(delegate);
// ensure that wrapper is a subtype of delegate
Preconditions.checkArgument(delegateClass.isAssignableFrom(wrapper.getClass()));
for (Method delegateMethod : delegateClass.getMethods()) {
if (checkSkipMethodForwardCheck(delegateMethod, skipMethodSet)) {
continue;
}
// find the correct method to substitute the bridge for erased generic types.
// if this doesn't work, the user need to exclude the method and write an additional test.
Method wrapperMethod = wrapper.getClass().getMethod(
delegateMethod.getName(),
delegateMethod.getParameterTypes());
// things get a bit fuzzy here, best effort to find a match but this might end up with a wrong method.
if (wrapperMethod.isBridge()) {
for (Method method : wrapper.getClass().getMethods()) {
if (!method.isBridge()
&& method.getName().equals(wrapperMethod.getName())
&& method.getParameterCount() == wrapperMethod.getParameterCount()) {
wrapperMethod = method;
break;
}
}
}
Class<?>[] parameterTypes = wrapperMethod.getParameterTypes();
Object[] arguments = new Object[parameterTypes.length];
for (int j = 0; j < arguments.length; j++) {
Class<?> parameterType = parameterTypes[j];
if (parameterType.isArray()) {
arguments[j] = Array.newInstance(parameterType.getComponentType(), 0);
} else if (parameterType.isPrimitive()) {
if (boolean.class.equals(parameterType)) {
arguments[j] = false;
} else if (char.class.equals(parameterType)) {
arguments[j] = 'a';
} else {
arguments[j] = (byte) 0;
}
} else {
arguments[j] = Mockito.mock(parameterType);
}
}
wrapperMethod.invoke(wrapper, arguments);
delegateMethod.invoke(Mockito.verify(delegate, Mockito.times(1)), arguments);
reset(delegate);
}
}
/**
* This is a best effort automatic test for method forwarding between a delegate and its wrapper, where the wrapper
* class is a subtype of the delegate. Methods can be remapped in case that the implementation does not call the
* original method. Remapping to null skips the method. This ignores methods that are inherited from Object.
*
* @param delegateClass the class for the delegate.
* @param wrapperFactory factory that produces a wrapper from a delegate.
* @param delegateObjectSupplier supplier for the delegate object passed to the wrapper factory.
* @param skipMethodSet set of methods to ignore.
* @param <D> type of the delegate
* @param <W> type of the wrapper
* @param <I> type of the object created as delegate, is a subtype of D.
*/
public static <D, W, I extends D> void testMethodForwarding(
Class<D> delegateClass,
Function<I, W> wrapperFactory,
Supplier<I> delegateObjectSupplier,
Set<Method> skipMethodSet) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Preconditions.checkNotNull(delegateClass);
Preconditions.checkNotNull(wrapperFactory);
Preconditions.checkNotNull(skipMethodSet);
I delegate = delegateObjectSupplier.get();
//check if we need to wrap the delegate object as a spy, or if it is already testable with Mockito.
if (!MockUtil.isSpy(delegate) || !MockUtil.isMock(delegate)) {
delegate = spy(delegate);
}
W wrapper = wrapperFactory.apply(delegate);
// ensure that wrapper is a subtype of delegate
Preconditions.checkArgument(delegateClass.isAssignableFrom(wrapper.getClass()));
for (Method delegateMethod : delegateClass.getMethods()) {
if (checkSkipMethodForwardCheck(delegateMethod, skipMethodSet)) {
continue;
}
// find the correct method to substitute the bridge for erased generic types.
// if this doesn't work, the user need to exclude the method and write an additional test.
Method wrapperMethod = wrapper.getClass().getMethod(
delegateMethod.getName(),
delegateMethod.getParameterTypes());
// things get a bit fuzzy here, best effort to find a match but this might end up with a wrong method.
if (wrapperMethod.isBridge()) {
for (Method method : wrapper.getClass().getMethods()) {
if (!method.isBridge()
&& method.getName().equals(wrapperMethod.getName())
&& method.getParameterCount() == wrapperMethod.getParameterCount()) {
wrapperMethod = method;
break;
}
}
}
Class<?>[] parameterTypes = wrapperMethod.getParameterTypes();
Object[] arguments = new Object[parameterTypes.length];
for (int j = 0; j < arguments.length; j++) {
Class<?> parameterType = parameterTypes[j];
if (parameterType.isArray()) {
arguments[j] = Array.newInstance(parameterType.getComponentType(), 0);
} else if (parameterType.isPrimitive()) {
if (boolean.class.equals(parameterType)) {
arguments[j] = false;
} else if (char.class.equals(parameterType)) {
arguments[j] = 'a';
} else {
arguments[j] = (byte) 0;
}
} else {
arguments[j] = Mockito.mock(parameterType);
}
}
wrapperMethod.invoke(wrapper, arguments);
delegateMethod.invoke(Mockito.verify(delegate, Mockito.times(1)), arguments);
reset(delegate);
}
}
private static boolean isMock(Link link) {
return new MockUtil().isMock(link);
}
private String qualifiedMethodName() {
return new MockUtil().getMockName(mock) + "." + method.getName();
}
/**
* Ignores stubbed methods of given mocks for the sake of verification.
* <p>
* Other words: all *stubbed* methods of given mocks are made *verfied* so that they don't get in a way during verifyNoMoreInteractions().
* <p>
* This method changes the input mocks! This method returns input mocks for convenience.
* <p>
* Example:
* <pre>
* //mocking lists for the sake of the example (if you mock List in real you will burn in hell)
* List mock1 = mock(List.class), mock2 = mock(List.class);
*
* //stubbing mocks:
* when(mock1.get(0)).thenReturn(10);
* when(mock2.get(0)).thenReturn(20);
*
* //using mocks by calling stubbed get(0) methods:
* System.out.println(mock1.get(0)); //prints 10
* System.out.println(mock2.get(0)); //prints 20
*
* //using mocks by calling clear() methods:
* mock1.clear();
* mock2.clear();
*
* //verification:
* verify(mock1).clear();
* verify(mock2).clear();
*
* //verifyNoMoreInteractions() fails because get() methods were not accounted for.
* try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
*
* //However, if ignore stubbed methods then we can verifyNoMoreInteractions()
* verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
*
* //Remember that ignoreStubs() *changes* the input mocks and returns them for convenience.
* <pre>
*
* @param mocks input mocks that will be changed
* @return the same mocks that were passed in as parameters
*/
public static Object[] ignoreStubs(Object... mocks) {
for (Object m : mocks) {
InvocationContainer invocationContainer = new MockUtil().getMockHandler(m).getInvocationContainer();
List<Invocation> ins = invocationContainer.getInvocations();
for (Invocation in : ins) {
InvocationMarker invocationMarker = new InvocationMarker();
if (in.stubInfo() != null) {
invocationMarker.markVerified(in, new CapturesArgumensFromInvocation() {
public void captureArgumentsFrom(Invocation i) {
//don't capture
}
});
}
}
}
return mocks;
}
protected boolean isMock(Object o) {
return new MockUtil().isMock(o);
}
@Test
//TODO split into separate
public void shouldReturnMockValueForInterface() throws Exception {
Object interfaceMock = values.returnValueFor(FooInterface.class);
assertTrue(new MockUtil().isMock(interfaceMock));
}