上次我们解析了mockito是怎么实现mock的,本次在上次的基础上使用bytebuddy仿写一下mock的过程。https://blog.csdn.net/qq_27886773/article/details/135502353
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Data
public static class TestMock {
private String name;
}
private static ThreadLocal<Process> processThreadLocal = new ThreadLocal<>();
private static ThreadLocal<Object> realObjectThreadLocal = new ThreadLocal<>();
@Test
public void testMyMock() throws InstantiationException, IllegalAccessException {
TestMock mock = myMock(new TestMock());
when(mock.getName()).thenReturn("mockTest");
System.out.println(mock.getName());
}
public TestMock myMock(TestMock realObject) throws InstantiationException, IllegalAccessException {
Class<? extends TestMock> dynamicType = new ByteBuddy()
.subclass(realObject.getClass())
//拦截所有的方法
.method(ElementMatchers.named("getName"))
//自定义拦截器
.intercept(MethodDelegation.to(new GeneralInterceptor()))
.make()
.load(realObject.getClass().getClassLoader())
.getLoaded();
realObjectThreadLocal.set(realObject);
return dynamicType.newInstance();
}
@Data
@AllArgsConstructor
public static class Process {
private boolean start;
private Object mockReturn;
private Object realReturn;
private String methodName;
public void thenReturn(Object mockReturn) {
this.mockReturn = mockReturn;
}
}
public Process when(Object methodReturn) {
Process process = processThreadLocal.get();
process.setStart(true);
process.setRealReturn(methodReturn);
return processThreadLocal.get();
}
public static class GeneralInterceptor {
@RuntimeType
public Object intercept(@AllArguments Object[] allArguments,
@Origin Method method, @This Object o) {
if (processThreadLocal.get() == null) {
processThreadLocal.set(new Process(false, null, null, method.getName()));
}
Process process = processThreadLocal.get();
if (!process.isStart() || !process.getMethodName().equals(method.getName())) {
try {
return method.invoke(realObjectThreadLocal.get(), allArguments);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
} else {
return processThreadLocal.get().getMockReturn();
}
}
}
}
mymock方法中,使用bytebuddy,mock了一个类,并且拦截他的getName方法。
when方法中,给当前过程设置设置真实的值
thenReturn方法中,给当前过程,设置mock的值
拦截器GeneralInterceptor,主要设置当前的过程,或者放回mock的数据。