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

クラスをモックすることはできますが、それをさらにモックしてクラス インスタンスMethodSignatureを返したいと思うと思います。Methodまあ、それMethodは final であるため、拡張することはできません。したがって、嘲笑することもできません。「モックされた」メソッドを表すために、テストクラスで偽のメソッドを作成できるはずです。私は通常、次のようにします。

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 に答える