Unit Testing Aspects

by mlaccetti on April 9, 2010

Something that I haven’t really run into is how to unit test an aspect – given how unique the circumstances are required to invoke such an event, I was at a bit of a loss. After some thinking and trial/error, I came up with a cut-down version of what the application uses – a limited Spring configuration, the Spring test suite, JUnit and a lot of assertions.

The Spring config is actually pretty trivial, as most of the magic happens using Annotations (@Component, @Aspect and @Order) – very little configuration lives in an XML file. Since I use Spring 3, I might even do away with the config file – we’ll see how that goes.

The interesting part is the unit test, which you can see here:

I use the Spring test runner, which means I can inject my configuration file, and can also autowire the necessary objects. In this case, I’m injecting a user DAO along with the Ehcache manager. My test then invokes the DAO and checks to see if the item was actually cached. Pretty simple, but took a while to get right. The one caveat is that you need to turn off things like Terracotta, or else things may be considered valid when they actually are not.

Leave a Comment

Previous post:

Next post: