Testing a Service with Mocks

Testing AOP applications seems difficult, but we'll give you a couple of techniques that simplify it. In this example, you'll learn how to use mock objects with aspects.

Why do I care?

When you use an aspect, it's often difficult to know if that aspect is working correctly. Since it's not main-line code, the testing strategy is not always clear. By mocking your aspect, you can confirm that it's fired when you expect it to be.

How do I do that?

We're going to create a test case, and call a target method within the test case (Examples Example 6-14 and Example 6-15).

Example 6-14. InterceptMe.java

// simple intercept to proxy
public interface InterceptMe {
    void interceptThisMethod( );
}

Example 6-15. MockInterceptorTest.java

public class MockInterceptorTest extends TestCase implements InterceptMe {
    public void interceptThisMethod( ) {
           // empty method
    }
}

Then, in our actual test method, we'll configure a proxy for the test case, and configure the proxy to intercept all the methods in our test interface (Example 6-16).

Example 6-16. ControllerTest.java

public void testLoggingInterceptor( ) throws Exception {
        Advice advice = new LoggingAround( );
        ProxyFactory proxyFactory = new ProxyFactory(this);
        proxyFactory.addAdvice(advice);
        InterceptMe target = (InterceptMe)proxyFactory.getProxy( );
        target.interceptThisMethod( );
}

Finally, we'll use a mock object to record our expected behavior, and verify the behavior when we're done. In this case, remember the definition of ...

Get Spring: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.