Building a Test-Friendly Interceptor

In this example, you'll learn how to build interceptors that do nothing but improve your ability to test code. Usually, a transaction interceptor does three things:

  1. Begins a transaction when a method starts.

  2. Rolls back a transaction when an exception is thrown.

  3. Commits the transaction when a method completes.

Of course, that's what you usually want to happen. Test cases are different animals, though. They're responsible for putting conditions back to the state where they were before a test case was fired, and they need to execute quickly.

For a test case, often it makes sense to replace the third step. You may instead want the transaction to roll back after the method completes. That way, you remove one of the most expensive database steps (the commit), and you also restore the database state to what it was before you executed the transaction.

How do I do that?

In Spring, it's easy to build this type of behavior into an interceptor, because you can build a custom interceptor. Example 7-29 shows the code for a transaction interceptor that rolls back.

Example 7-29. TestTxInterceptor.java

public class TestTxInterceptor implements MethodInterceptor { private PlatformTransactionManager platformTransactionManager; public PlatformTransactionManager getPlatformTransactionManager( ) { return platformTransactionManager; } public void setPlatformTransactionManager(PlatformTransactionManager platformTransactionManager) { this.platformTransactionManager = platformTransactionManager; ...

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.