7

我正在尝试模拟 ProceedingJoinPoint 类,但在模拟方法时遇到了困难。

这是调用模拟类的代码:

...
// ProceedingJoinPoint joinPoint

Object targetObject = joinPoint.getTarget();
try {

  MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  Method method = signature.getMethod();

  ...
  ...

到目前为止,这是我模拟的课堂尝试......

accountService = new AccountService();
ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
when(joinPoint.getTarget()).thenReturn(accountService);

我现在不确定如何模拟签名以获得什么方法?

when(joinPoint.getSignature()).thenReturn(SomeSignature); //???

有任何想法吗?

4

1 回答 1

22

Well, you can mock the MethodSignature class, but I imagine you want to further mock that to return a Method class instance. Well, since Method is final, it cannot be extended, and therefore cannot be mocked. You should be able to create a bogus method in your test class to represent your 'mocked' method. I usually do it something like this:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

import java.lang.reflect.Method;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MyTest {
    AccountService accountService;

    @Test
    public void testMyMethod() {
        accountService = new AccountService();

        ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
        MethodSignature signature = mock(MethodSignature.class);

        when(joinPoint.getTarget()).thenReturn(accountService);
        when(joinPoint.getSignature()).thenReturn(signature);
        when(signature.getMethod()).thenReturn(myMethod());
        //work with 'someMethod'...
    }

    public Method myMethod() {
        return getClass().getDeclaredMethod("someMethod");
    }

    public void someMethod() {
        //customize me to have these:
        //1. The parameters you want for your test
        //2. The return type you want for your test
        //3. The annotations you want for your test
    }
}
于 2013-08-22T14:09:20.437 回答