Junit 如何模拟AspectJ类?

Junit 如何模拟AspectJ类?,junit,aspectj,spring-aop,Junit,Aspectj,Spring Aop,问题是,我无法在运行单元测试时模拟这个aspectj类,因为在模拟它之前,不知何故它被注入了上下文中 示例代码- @Aspect public class ExampleAspect { @Around ("execution * com.*.*.*(..)") public void printResult(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("Before Method

问题是,我无法在运行单元测试时模拟这个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类或禁用单元测试用例的aspectj?谢谢

您不需要模拟,因为您可以利用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();
    }
}

您不需要模拟,因为您可以利用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();
    }
}

谢谢,但我现在得到以下错误-建议必须在方面类型中声明:冒犯方法您的切入点有错误。试试这个
@Around(“execution(*com.*.*(..)”)
。示例中给出的切入点有一个输入错误。我可以使用切入点运行,但单元案例失败。遇到一篇关于上述错误的帖子-。我使用的是MockitoJUnitRunner,现在将单元用例更改为使用SpringJUnit4ClassRunner,并在测试配置中创建bean,但bean没有创建。我对这一点还不熟悉,并进一步尝试。谢谢,但我现在得到以下错误-建议必须在方面类型中声明:冒犯方法您的切入点有错误。试试这个
@Around(“execution(*com.*.*(..)”)
。示例中给出的切入点有一个输入错误。我可以使用切入点运行,但单元案例失败。遇到一篇关于上述错误的帖子-。我使用的是MockitoJUnitRunner,现在将单元用例更改为使用SpringJUnit4ClassRunner,并在测试配置中创建bean,但bean没有创建。我对这一点还不熟悉,并在进一步尝试。