Mockito 源码分析
本文主要以 Mockito 2.9.0 为基础进行分析,如有bug请大家指正。
Mockito 主要过程如下图所示:
Mockito架构如上图所示,通过对目标类进行创建 proxy 类,并添加相应的函数拦截方式,然后实例化,即为最终生成的 mock 对象。
通过 Interceptor 类来对目标类中的特殊函数乃至特殊参数进行特殊返回值的定义。
入口分析
通过官方示例,可以看出 Mockito 的使用都是依赖于 Annotation 进行完成的,因此程序的入口也由其来承担。那它们是怎么进行 Annotation 解析的呢?
示例如下:
@RunWith(MockitoJUnitRunner.class)
public class UnitTest {
private static final String FAKE_STRING = "HELLO WORLD";
@Mock
Context mMockContext;
@Before
public void setup() {
when(mMockContext.getString(R.string.app_name))
.thenReturn(FAKE_STRING);
}
@Test
public void test() {
String text = mMockContext.getString(R.string.app_name);
System.out.println(text);
}
}
在 Mockito 1.x 版本中通过 BlockJUnit4ClassRunner 来判定 JUnit版本(是否4~5以上),因此通过 BlockJUnit4ClassRunner 及 JUnit44RunnerImpl 中为初始化过程添加MockitoAnnotations.initMocks(target); 这样来兼容老版本 JUnit 。
而在 Mockito 2.9.x 中则使用仅仅考虑JUnit 4以上的版本。因此如下图所示:
从而在代码中的 Annotations 相关的标记即可被发现。
架构分析
在 Mockito 中主要的类为 Mockito ,其中主要用来处理 mock 函数的相关实现。具体类图如下:
从类图结构上来看, Mockito 通过 ByteBuddy 来创建 mock 类并进行实例化 proxy 对象。
<b> 老版本中使用的是 cglib 的方式来进行创建子类 </b>
其中主要通过接口类ClassCreatingMockMaker来创建proxy类。
函数返回值分析
在 Mockito 中可以通过如下方式来进行返回值的 mock, 如下:
when(mMockContext.getString(R.string.app_name)).thenReturn(FAKE_STRING);
上述事项主要是通过 ThreadSafeMockingProgress 中 MockingProgressImpl 来获取当前调用过程中的 OngoingStubbing 来缓存其执行结果。具体过程如下图:
Mock 生成代理 Object 时序图在 SubclassBytecodeGenerator 中通过重写父类函数的实现来拦截对应函数的返回值,具体类的声明如下所示:
@Override
public <T> Class<? extends T> mockClass(MockFeatures<T> features) {
DynamicType.Builder<T> builder =
byteBuddy.subclass(features.mockedType)
.name(nameFor(features.mockedType))
.ignoreAlso(isGroovyMethod())
.annotateType(features.mockedType.getAnnotations())
.implement(new ArrayList<Type>(features.interfaces))
.method(matcher)
.intercept(to(DispatcherDefaultingToRealMethod.class))
.transform(withModifiers(SynchronizationState.PLAIN))
.attribute(INCLUDING_RECEIVER)
.method(isHashCode())
.intercept(to(MockMethodInterceptor.ForHashCode.class))
.method(isEquals())
.intercept(to(MockMethodInterceptor.ForEquals.class))
.serialVersionUid(42L)
.defineField("mockitoInterceptor", MockMethodInterceptor.class, PRIVATE)
.implement(MockAccess.class)
.intercept(FieldAccessor.ofBeanProperty());
if (features.serializableMode == SerializableMode.ACROSS_CLASSLOADERS) {
builder = builder.implement(CrossClassLoaderSerializableMock.class)
.intercept(to(MockMethodInterceptor.ForWriteReplace.class));
}
if (readReplace != null) {
builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectInputStream.class)
.throwing(ClassNotFoundException.class, IOException.class)
.intercept(readReplace);
}
ClassLoader classLoader = new MultipleParentClassLoader.Builder()
.append(features.mockedType)
.append(features.interfaces)
.append(currentThread().getContextClassLoader())
.append(MockAccess.class, DispatcherDefaultingToRealMethod.class)
.append(MockMethodInterceptor.class,
MockMethodInterceptor.ForHashCode.class,
MockMethodInterceptor.ForEquals.class).build(MockMethodInterceptor.class.getClassLoader());
if (classLoader != features.mockedType.getClassLoader()) {
assertVisibility(features.mockedType);
for (Class<?> iFace : features.interfaces) {
assertVisibility(iFace);
}
builder = builder.ignoreAlso(isPackagePrivate()
.or(returns(isPackagePrivate()))
.or(hasParameters(whereAny(hasType(isPackagePrivate())))));
}
return builder.make()
.load(classLoader, loader.getStrategy(features.mockedType))
.getLoaded();
}
在 SubclassByteBuddyMockMaker 中创建根据上述内容实例化出对应的 proxy 对象,并对相应的实例化字段进行赋值,具体内容参见 createMock 函数的实现,如下所示:
@Override
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
// 创建对应的代理类
Class<? extends T> mockedProxyType = createMockType(settings);
Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(settings);
T mockInstance = null;
try {
// 实例化代理对象
mockInstance = instantiator.newInstance(mockedProxyType);
MockAccess mockAccess = (MockAccess) mockInstance;
// 注册 mockMethodInterceptor 实例
mockAccess.setMockitoInterceptor(new MockMethodInterceptor(asInternalMockHandler(handler), settings));
return ensureMockIsAssignableToMockedType(settings, mockInstance);
} catch (ClassCastException cce) {
throw new MockitoException(join(
"ClassCastException occurred while creating the mockito mock :",
" class to mock : " + describeClass(settings.getTypeToMock()),
" created class : " + describeClass(mockedProxyType),
" proxy instance class : " + describeClass(mockInstance),
" instance creation by : " + instantiator.getClass().getSimpleName(),
"",
"You might experience classloading issues, please ask the mockito mailing-list.",
""
), cce);
} catch (org.mockito.internal.creation.instance.InstantiationException e) {
throw new MockitoException("Unable to create mock instance of type '" + mockedProxyType.getSuperclass().getSimpleName() + "'", e);
}
}
具体接口调用的拦截过程,参见 bytebuddy 拦截过程,下面是个简单的拦截例子,如下所示:
Class<?> dynamicType = new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("Hello World!"))
.make()
.load(getClass().getClassLoader())
.getLoaded();
assertThat(dynamicType.newInstance().toString(), is("Hello World!"));
上述方式可以固定返回 "Hello World"。
类似上述内容,在 Mockito 中会主动调用 MockMethodInterceptor 中的 doIntercept 函数中,从而最终调用 InternalMockHandler.handle() 函数,其中含有调用参数等信息。
因此当mock代理对象的函数被调用之后,最终会调用MockHandlerImpl.handle() 函数,具体实现如下:
public Object handle(Invocation invocation) throws Throwable {
if (invocationContainerImpl.hasAnswersForStubbing()) {
// stubbing voids with doThrow() or doAnswer() style
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(
mockingProgress().getArgumentMatcherStorage(),
invocation
);
invocationContainerImpl.setMethodForStubbing(invocationMatcher);
return null;
}
VerificationMode verificationMode = mockingProgress().pullVerificationMode();
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(
mockingProgress().getArgumentMatcherStorage(),
invocation
);
mockingProgress().validateState();
// if verificationMode is not null then someone is doing verify()
if (verificationMode != null) {
// We need to check if verification was started on the correct mock
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
if (((MockAwareVerificationMode) verificationMode).getMock() == invocation.getMock()) {
VerificationDataImpl data = createVerificationData(invocationContainerImpl, invocationMatcher);
verificationMode.verify(data);
return null;
} else {
// this means there is an invocation on a different mock. Re-adding verification mode
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
mockingProgress().verificationStarted(verificationMode);
}
}
// prepare invocation for stubbing
invocationContainerImpl.setInvocationForPotentialStubbing(invocationMatcher);
OngoingStubbingImpl<T> ongoingStubbing = new OngoingStubbingImpl<T>(invocationContainerImpl);
mockingProgress().reportOngoingStubbing(ongoingStubbing);
// look for existing answer for this invocation
StubbedInvocationMatcher stubbedInvocation = invocationContainerImpl.findAnswerFor(invocation);
notifyStubbedAnswerLookup(invocation, stubbedInvocation);
if (stubbedInvocation != null) {
stubbedInvocation.captureArgumentsFrom(invocation);
return stubbedInvocation.answer(invocation);
} else {
Object ret = mockSettings.getDefaultAnswer().answer(invocation);
DefaultAnswerValidator.validateReturnValueFor(invocation, ret);
// redo setting invocation for potential stubbing in case of partial
// mocks / spies.
// Without it, the real method inside 'when' might have delegated
// to other self method and overwrite the intended stubbed method
// with a different one. The reset is required to avoid runtime exception that validates return type with stubbed method signature.
invocationContainerImpl.resetInvocationForPotentialStubbing(invocationMatcher);
return ret;
}
}
这样在调用之后,会通过 mockingProgress().reportOngoingStubbing(ongoingStubbing); 函数调用来保存当前执行的函数信息,以及相关参数的信息,因此回到文章开头,使用 when 函数进行函数调用返回值的固定方式就通过 mockingProcess() 中获取 OngoingStubbing 对象,并设定相应的返回参数即可完成返回默认值或固定值的操作。