如何模拟AspectJ类?

时间:2017-11-10 00:27:16

标签: junit aspectj spring-aop

问题是我在运行单元测试时无法模拟这个aspectj类,因为在我模拟它之前它会以某种方式注入上下文中。

示例代码 -

@Aspect  
public class ExampleAspect {

@Around ("execution * com.*.*.*(..)") 
public void printResult(ProceedingJoinPoint joinPoint) throws Throwable {
       System.out.println("Before Method Execution");
       joinPoint.proceed();
      System.out.println("After Method Execution");
     }    }

测试课 -

public class ClassATest 
{
    @Mock
    private ExampleAspect mockExampleAspect;

    private ClassA testClass;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        Mockito.doNothing().when(mockExampleAspect).printResult(anyList());
        testClass = new ClassA();
    }

    @Test
    public void test() {
      // before and after methodA() is executed it is intercepted by the bean of ExampleAspect
      testClass.methodA();
    }
}

我能够成功使用这个方面。问题在于单元测试用例。我如何模拟这个方面的类或禁用单元测试用例的aspectj?感谢

1 个答案:

答案 0 :(得分:0)

您不需要模拟,因为您可以利用Spring框架的AspectJProxyFactory类来测试您的方面。这是一个简单的例子,

public class ClassATest {

    private ClassA proxy;

    @Before
    public void setup() {
        ClassA target = new ClassA();
        AspectJProxyFactory factory = new AspectJProxyFactory(target);
        ExampleAspect aspect = new ExampleAspect();
        factory.addAspect(aspect);
        proxy = factory.getProxy();
    }

    @Test
    public void test() {
        proxy.methodA();
    }
}