2012-11-06 57 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