单元测试Spring @Around AOP方法 [英] Unit testing Spring @Around AOP methods

查看:560
本文介绍了单元测试Spring @Around AOP方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以对大多数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上调用方法,并对aspectproxytarget进行断言.

... then you can call methods on proxy, and make assertions about aspect, proxy and target.

这篇关于单元测试Spring @Around AOP方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆