问题描述
我可以对大多数Spring类进行单元测试,而无需执行Spring工作".
I can unit test most of my Spring classes without needing to do Spring "stuff".
我也可以在不使用Spring的情况下对@Before建议方法进行单元测试:
I can unit test @Before advice methods without using Spring too:
示例代码:
@Before("execution(* run(..)) && " + "" +
"target(target) && " +
"args(name)")
public void logName(Object target, String name) {
logger.info("{} - run: {}", target, name);
}
示例测试:
@Test
public void testLogName() {
aspect.setLogger(mockLogger);
aspect.logName(this,"Barry");
assertTrue(mockLogger.hasLogged("TestAspect - run: Barry"));
}
但是@Around建议处理ProceedingJoinPoint对象:
However @Around advice deals with a ProceedingJoinPoint object:
@Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
我不知道如何实例化ProceedingJoinPoint对象.如何在不启动整个Spring应用程序上下文的情况下测试此类?
I don't know how to instantiate a ProceedingJoinPoint object. How do I test this class without starting a whole Spring application context?
推荐答案
您可以通过以编程方式创建代理来测试Spring Aspect:
You can test a Spring Aspect by creating a proxy programatically:
MyInterface target = new MyClass();
AspectJProxyFactory factory = new AspectJProxyFactory(target);
MyAspect aspect = new MyAspect(arg);
factory.addAspect(aspect);
MyInterface proxy = factory.getProxy();
...然后可以在proxy
上调用方法,并对aspect
,proxy
和target
进行断言.
... then you can call methods on proxy
, and make assertions about aspect
, proxy
and target
.
这篇关于单元测试Spring @Around AOP方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!