Mock ProceedingJoinPoint Signature

↘锁芯ラ 提交于 2021-02-07 06:46:15

问题


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?


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/18381877/mock-proceedingjoinpoint-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!