我试图嘲弄一个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); //???
有任何想法吗?
那么,你可以嘲笑MethodSignature
类,但我想你想进一步嘲弄,要返回Method
类的实例。那么,既然Method
是最终的,它不能扩展,因此不能被嘲笑。你应该能够在您的测试类来创建一个伪造的方法来表示你的“嘲笑”的方法。我通常做的是这样的:
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
}
}