use of org.mockito.plugins.InstantiatorProvider2 in project dexmaker by linkedin.
the class InlineDexmakerMockMaker method createMock.
@Override
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
Class<T> typeToMock = settings.getTypeToMock();
Set<Class<?>> interfacesSet = settings.getExtraInterfaces();
Class<?>[] extraInterfaces = interfacesSet.toArray(new Class[interfacesSet.size()]);
InvocationHandlerAdapter handlerAdapter = new InvocationHandlerAdapter(handler);
T mock;
if (typeToMock.isInterface()) {
// support interfaces via java.lang.reflect.Proxy
Class[] classesToMock = new Class[extraInterfaces.length + 1];
classesToMock[0] = typeToMock;
System.arraycopy(extraInterfaces, 0, classesToMock, 1, extraInterfaces.length);
// newProxyInstance returns the type of typeToMock
mock = (T) Proxy.newProxyInstance(typeToMock.getClassLoader(), classesToMock, handlerAdapter);
} else {
boolean subclassingRequired = !interfacesSet.isEmpty() || Modifier.isAbstract(typeToMock.getModifiers());
// Add entry hooks to non-abstract methods.
classTransformer.mockClass(MockFeatures.withMockFeatures(typeToMock, interfacesSet));
Class<? extends T> proxyClass;
Instantiator instantiator = Mockito.framework().getPlugins().getDefaultPlugin(InstantiatorProvider2.class).getInstantiator(settings);
if (subclassingRequired) {
try {
// support abstract methods via dexmaker's ProxyBuilder
proxyClass = ProxyBuilder.forClass(typeToMock).implementing(extraInterfaces).onlyMethods(getMethodsToProxy(settings)).withSharedClassLoader().buildProxyClass();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new MockitoException("Failed to mock " + typeToMock, e);
}
try {
mock = instantiator.newInstance(proxyClass);
} catch (org.mockito.creation.instance.InstantiationException e) {
throw new MockitoException("Unable to create mock instance of type '" + proxyClass.getSuperclass().getSimpleName() + "'", e);
}
ProxyBuilder.setInvocationHandler(mock, handlerAdapter);
} else {
try {
mock = instantiator.newInstance(typeToMock);
} catch (org.mockito.creation.instance.InstantiationException e) {
throw new MockitoException("Unable to create mock instance of type '" + typeToMock.getSimpleName() + "'", e);
}
}
}
mocks.put(mock, handlerAdapter);
return mock;
}
Aggregations