Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

Unit testing Spring @Around AOP methods

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?

question from:https://stackoverflow.com/questions/11436600/unit-testing-spring-around-aop-methods

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...