It’s very important that whenever you use the AbstractTransactionalStringContextTests
class that a PlatformTransactionManagercan be found, by type, in the ApplicationContext
created for the test. This class is able to run without a transaction manager; however, this will
likely lead to unwanted behavior, and most likely behavior that is different than production
deployment.
If you wish to ignore the fact that no transaction manager exists, you must turn off
dependency checking, as shown in Listing 10-15. The AbstractDependencyInjectionSpring➥
ContextTestsby default will attempt to account for all dependencies by type, but you can
change this behavior with the setDependencyCheck()method called from the constructor of
your test class.
Listing 10-15.Turning Off Dependency Checking If No Transaction Manager Exists
public HomeControllerIntegrationTest() {
setDependencyCheck(false);
}
The ApplicationContextis configured from the list of resource names returned by the
getConfigLocations()abstract method. All of your test classes must implement this method
and return one or more resource names pointing to ApplicationContextconfiguration files.
All of these files will be combined into a single ApplicationContextto be used during testing.
Any Dependency Injection is performed using this ApplicationContextas a source.
■Tip In our experience, it’s best to use resource names relative to the classpath, as that makes it easier to
run the tests in different environments and IDEs.
The Spring integration test base classes override the setUp() method and mark it as final,
but do provide life cycle callback methods for subclasses that require per-test method initial-
ization. For transactional tests, two methods are provided: onSetupBeforeTransaction()to be
called before the transaction is started, and onSetupAfterTransaction() to be called after the
transaction is started. Both callbacks are called inside setUp(), and thus before every single
test method.
For our example, we have implemented onSetupBeforeTransaction()in order to simply
initialize any required testing stubs.
Because the transactional test cases are subclasses of AbstractDependencyInjection➥
SpringContextTests, we provide a setHomeController()method so that our test class can
avoid the manual lookup of dependencies from the ApplicationContext. The dependencies
are resolved by type via the autowiring algorithm, and will be re-injected before every test
method. Of course, because the Controllerclass originates from the ApplicationContext,
all of its dependencies will be injected as well. The assumption at this point is that the class
under test should be fully initialized as if it were running in production.
The actual test method, testRequest(), is written and run just like any other JUnit test
method. However, during the method a transaction is live, and unless setComplete()is called,
at the end of testRequest()the transaction will be rolled back.
306 CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS