当我使用Mockito时,为什么我的测试方法返回null?

时间:2012-11-06 20:22:48

标签: junit mockito

我正在尝试使用Mockito 1.9.x进行模拟,以下代码恰好位于Spring AOP连接点的advice方法中

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()时测试的方法中为null。thenReturn()?

1 个答案:

答案 0 :(得分:3)

该方法使用signature返回的pjp.getSignature()而非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);
相关问题