Skip to Main Content
Spring: A Developer's Notebook
book

Spring: A Developer's Notebook

by Bruce Tate, Justin Gehtland
April 2005
Intermediate to advanced content levelIntermediate to advanced
216 pages
4h 44m
English
O'Reilly Media, Inc.
Content preview from Spring: A Developer's Notebook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaBeans Unleashed

JavaBeans Unleashed

Dr. Donald Doherty, Rick Leinecker
Beginning Spring

Beginning Spring

Mert Caliskan, Kenan Sevindik, Rod Johnson, Jürgen Höller
Hibernate Search in Action

Hibernate Search in Action

Emmanuel Bernard, John Griffin

Publisher Resources

ISBN: 0596009100Supplemental ContentErrata Page