在方法周围的Spring方面内部模拟方法调用

时间:2020-03-27 17:30:41

标签: mockito

我想在@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类对象。任何人都可以在这里帮忙。

1 个答案:

答案 0 :(得分:0)

您可以使用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
}