Testing Spring AOP code

In Using the Spring AOP Framework with EJB Components, Eugene Kuleshov presents a really nice way to test Spring AOP configuration code and advices. When you use Spring AOP use can easily test your target objects with unit tests, but how do you test the weaved code?

In the above article Eugene Kuleshov uses unit tests that reference the Spring ApplicationContext that has the AOP configuration code. Then at the setup method of the TestCase class he registers a custom BeanPostProcessor that provides mock implementations for the target objects. At the test methods he trains the mock objects and tests the all the AOP code except the target objects.

I really liked the trick with the custom BeanPostProcessor to provide the mock objects. I’ll probably start using this trick in my tests really soon.

BTW Using the Spring AOP Framework with EJB Components also provides lots of information on how to effectively use Spring in a EJB 2.x environment. If you are maintaining EJB 2.x applications and you want to make your applications more testable over time you should probably read this article.

AOP and legacy code

AOP is great when you want to enhance an application but you do not want to modify its source code. This restriction may come for maintainability reasons.

A good example of this can be found in the article “Using Aspects to autonomic-enable legacy applications” by Brian Temple published at developerWorks.

Quote from the article’s intro:

Learn how to use Aspects to generate Common Base Events in any legacy Java application, without modifying the original application source. This article shows you how and also provides an example framework that can be used with your applications today.

To apply AOP of course you have to have access to the source code, but you do not necessary need to change it. AOP is a meta-programming system that adds functionality (advices) to certain points in the flow of execution (joinpoints) of the application. To match those points you have to refer to code constructs like method invocations, access to a package, throwing of an exception, etc so you need to know the names of methods, packages, exceptions, etc.