Robert Munteanu Robert Munteanu - 23 days ago 6
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

@Aspect
declarations with Spring 2.5.6.




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

Answer

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

Created a Spring-aware JUnit test

@RunWith(SpringJUnit4ClassRunner.class)
@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"/>
        </property>
    </bean>
    <bean class="DummyService"/>
    

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

@Autowired
private DummyService _dummyService;

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

    _dummyService.adminOnly();
}
Comments