gpt4 book ai didi

java - 模拟 ProceedingJoinPoint 签名

转载 作者:搜寻专家 更新时间:2023-11-01 01:13:14 29 4
gpt4 key购买 nike

我正在尝试模拟一个 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
}
}

关于java - 模拟 ProceedingJoinPoint 签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18381877/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com