2012-11-06 125 views
0

我试图嘲弄,使用的1.9.x的Mockito,下面的代码这恰好是在Spring AOP的建议方法连接点当我使用Mockito的时候,为什么我的测试方法返回null?

protected void check(ProceedingJoinPoint pjp) { 
    final Signature signature = pjp.getSignature(); 
    if (signature instanceof MethodSignature) { 
     final MethodSignature ms = (MethodSignature) signature; 
     Method method = ms.getMethod(); 
     MyAnnotation anno = method.getAnnotation(MyAnnotation.class); 
     if (anno != null) { 
     ..... 
} 

以下是我对模拟到目前为止

ProceedingJoinPoint pjp = mock(ProceedingJoinPoint.class); 
Signature signature = mock(MethodSignature.class); 
when(pjp.getSignature()).thenReturn(signature); 

MethodSignature ms = mock(MethodSignature.class); 
Method method = this.getClass().getMethod("fakeMethod"); 
when(ms.getMethod()).thenReturn(method); 

.... 

所以我必须在我的测试类中使用fakeMethod()创建一个Method实例,因为你不能模拟/间谍最终类。使用调试器,我发现在调用“this.getClass()。getMethod(”fakeMethod“);”但在我的check()方法中,在它执行“Method method = ms.getMethod();”行之后,方法为null。这会在下一行产生NPE。

为什么我的方法对象在测试用例中不是null,而是在使用when()。thenReturn()时测试的方法中是null?

回答

2

该方法使用pjp.getSignature()返回的signature而不是ms,其中已添加模拟MethodSignature。试试:

ProceedingJoinPoint pjp = mock(ProceedingJoinPoint.class); 
MethodSignature signature = mock(MethodSignature.class); 
when(pjp.getSignature()).thenReturn(signature); 

Method method = this.getClass().getMethod("fakeMethod"); 
when(signature.getMethod()).thenReturn(method); 
+0

就是这样。谢谢! – wxkevin