1

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

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();”行后为空 这会导致下一行出现 NPE。

为什么我的方法对象在测试用例中为非空,但在使用 when().thenReturn() 时我正在测试的方法中为空?

4

1 回答 1

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);
于 2012-11-06T21:54:58.037 回答