在下面显示的 unittest 类中,一个测试失败,另一个测试成功。这两个测试都创建了一个CGLIB
带有拦截器模拟的对象,并尝试验证拦截器是否与之交互。测试在使用 CGLIB 动态子类化的类上有所不同。成功的测试子类化一个普通的 Java 接口;失败的子类是一个动态子类(使用创建Mockito
)。为什么第一次测试失败了?
谢谢。
public class ATest {
@Test
// This test fails.
public void cannotCallMethodOnMockWrapper() throws Throwable {
final Class<? extends Bar> c = Mockito.mock(Bar.class).getClass();
verifyInterceptorIsInvokedOnCallToObjectOfEnhanced(c);
}
@Test
// This test succeeds.
public void interceptorIsCalled() throws Throwable {
final Class<? extends Bar> c = Bar.class;
verifyInterceptorIsInvokedOnCallToObjectOfEnhanced(c);
}
private void verifyInterceptorIsInvokedOnCallToObjectOfEnhanced(
final Class<? extends Bar> c) throws Throwable {
final MethodInterceptor interceptor = Mockito.mock(
MethodInterceptor.class);
final Bar wrapper = (Bar) Enhancer.create(c, interceptor);
// Here is where the failing test chokes with exception:
// NoSuchMethodError
wrapper.foo();
verifyInterceptIsCalledOn(interceptor);
}
private void verifyInterceptIsCalledOn(
final MethodInterceptor interceptor) throws Throwable {
verify(interceptor).intercept(any(), any(Method.class),
any(Object[].class), any(MethodProxy.class));
}
public static interface Bar {
void foo();
}
}
更新:
失败的堆栈跟踪
java.lang.NoSuchMethodError: java.lang.Object.foo()V
at ATest$Bar$$EnhancerByMockitoWithCGLIB$$2e1d601f.foo(<generated>)
at ATest.verifyInterceptorIsInvokedOnCallToObjectOfEnhanced(ATest.java:37)
at ATest.cannotCallMethodOnMockWrapper(ATest.java:19)
此外,关于 Mockito 模拟是否是 CGLIB 增强类,下面的测试(失败)似乎表明它不是:
public class ATest {
@Test
public void mockitoMockIsCGLIBEnhanced() {
assertTrue(Enhancer.isEnhanced(Mockito.mock(Bar.class).getClass()));
}
public static interface Bar {
void foo();
}
}