I am trying to mock a ProceedingJoinPoint class and I am having difficulty mocking a method.
Here is the code that is calling the mock class:
...
// ProceedingJoinPoint joinPoint
Object targetObject = joinPoint.getTarget();
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
...
...
and here is my mocked class attempt so far...
accountService = new AccountService();
ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
when(joinPoint.getTarget()).thenReturn(accountService);
I am now not sure how to mock a signature to get what a method?
when(joinPoint.getSignature()).thenReturn(SomeSignature); //???
Any ideas?
Here is the code that is calling the mock class: ... // ProceedingJoinPoint joinPoint Object targetObject = joinPoint. getTarget(); try { MethodSignature signature = (MethodSignature) joinPoint. getSignature(); Method method = signature.
getSignature() method returns everything you need to get the actual class name, method name, return type and parameters for the joinpoint. Java aspect programming is a powerful tool.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With