MWr*_*ght 4 java spring aspectj mocking mockito
我试图模拟ProceedingJoinPoint类,我很难嘲笑一个方法.
以下是调用mock类的代码:
...
// ProceedingJoinPoint joinPoint
Object targetObject = joinPoint.getTarget();
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
...
...
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我嘲笑的课堂尝试......
accountService = new AccountService();
ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
when(joinPoint.getTarget()).thenReturn(accountService);
Run Code Online (Sandbox Code Playgroud)
我现在不确定如何模拟签名以获得什么方法?
when(joinPoint.getSignature()).thenReturn(SomeSignature); //???
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
nic*_*ild 14
好吧,你可以模拟这个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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5099 次 |
| 最近记录: |