首页 > 解决方案 > 在方法周围的弹簧方面模拟方法调用

问题描述

我想在 @Aspect 类中模拟方法调用。

我有班级学生。

public class Student{
public String getName()
{
//
}
}

I have an Aspect class 

@Aspect
@Component
public class StudentAspect{

@Autowired
B b;
@Around( // the Student class get method)
public void around(ProceedingJoinPoint joinPoint)
{
b.doSomething();
}
}

我想使用 Mockito 测试 StudentAspect。我以编程方式为 Student 类创建了一个代理,以便我可以触发 StudentAspect 类。但是,我无法模拟 B 类对象。任何人都可以在这里帮忙。

标签: mockito

解决方案


您可以使用 AspectJProxyFactory 来测试方面。基于 AspectJ 的代理工厂,允许以编程方式构建包含 AspectJ 方面的代理。

例子:

@Test
public void testStudentAspect() {
    B testBean = new B();

    AspectJProxyFactory factory = new AspectJProxyFactory();
    factory.setTarget(testBean);

    CounterAspect myCounterAspect = new CounterAspect();
    factory.addAspect(myCounterAspect);

    ITestBean proxyTestBean = factory.getProxy();

    proxyTestBean.doSomething();

    //assert
}

推荐阅读