Robert Munteanu Robert Munteanu - 2 months ago 17
Java Question

Testing a Spring AOP Aspect

When writing aspects, how can I test that they do match and that they are invoked when I want them to?

I'm using

declarations with Spring 2.5.6.

I don't care about the functionality, that's extracted and tested otherwise.


I ended up creating something which is a bit of an integration test, in the following way:

Created a Spring-aware JUnit test

@ContextConfiguration(locations = { "aspects-test.xml" })
public class SomeAspectTest {


Created a spring configuration for this test which:

  • enables @AspectJ usage;
  • configures my aspect with dummy dependencies
  • declares a bean which should be picked up by the aspect

    <aop:aspectj-autoproxy />
    <bean class="SomeAspect">
        <property name="userDetailsSource">
                <bean class="StubUserDetailsSource"/>
    <bean class="DummyService"/>

In the unit test I retrieve the dummy service and invoke its methods

private DummyService _dummyService;

@Test(expected = ApplicationSecurityException.class)
public void adminOnlyFails() throws ApplicationSecurityException {