【问题标题】:How to mock AspectJ class?如何模拟 AspectJ 类?
【发布时间】:2017-11-10 00:27:16
【问题描述】:

问题是我无法在运行单元测试时模拟这个 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?谢谢

【问题讨论】:

    标签: junit aspectj spring-aop


    【解决方案1】:

    您不需要模拟,因为您可以利用 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.*.*.*(..))")
    • 示例中给出的切入点有错字。我可以使用切入点运行,但单元案例失败。遇到上述错误的一篇帖子 - stackoverflow.com/questions/31329009/… 。我正在使用 MockitoJUnitRunner,现在将单元案例更改为使用 SpringJUnit4ClassRunner 并在我的测试配置中创建 bean,但未创建 bean。我对此很陌生,并进一步尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多