Unit testing Spring @Around AOP methods

slim picture slim · Jul 11, 2012 · Viewed 27.5k times · Source

I can unit test most of my Spring classes without needing to do Spring "stuff".

I can unit test @Before advice methods without using Spring too:

Example code:

@Before("execution(* run(..)) && " + "" +
          "target(target) && " +
        "args(name)")
public void logName(Object target, String name) {
    logger.info("{} - run: {}", target, name);
}

Example test:

@Test
public void testLogName() {
    aspect.setLogger(mockLogger);
    aspect.logName(this,"Barry");
    assertTrue(mockLogger.hasLogged("TestAspect - run: Barry"));
}

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;
 }

I don't know how to instantiate a ProceedingJoinPoint object. How do I test this class without starting a whole Spring application context?

Answer

slim picture slim · Jul 11, 2012

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();

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