I'm trying to setup some best practices how to organize your Spring configuration together with testing so it doesn't become your nightmare.
My 2 main goals are:
- Minimize XML configuration. I'm most concerned about a lot of XML files for test purposes.
- In tests use default configuration as a basis (same as in a production), so you mock what you need implicitly.
Best practices are:
- Use annotations autowiring as a default configuration for dependency injection. In a default Spring XML configuration there are no bean definitions for services, resources etc.
- Move all context:component-scan into a applicatonConfig-main.xml so it can be mocked in tests. There should be no other configuration in this file.
- Move all properties that can differ between environments from XML to properties file that can be accessed using property file placeholder together with spring.active.profiles property as described here: http://maciejwalkowiak.pl/blog/2012/03/27/spring-3-1-profiles-and-tomcat-configuration/
- Move all Spring configuration files to one folder. For example if your app consists of projects like persistence, model etc. All XML config files dedicated for these projects are moved to web app project/
For tests:
- Use a default Spring configuration for setting up app context and set mocks programmatically in test setup rather then using separate Spring configuration. In this approach we can still use default Spring configuration, no need to maintain additional Spring config file.
- If 1 is difficult for some reasons, write a separate Spring XML file with own set and mocks definition. What is important here is that this file does nothing more than mock settings and the rest of properties is the same as in default configuration.
There are a lot of tutorials about Spring unit testing, but when it comes to the real life maintenance problem always appear.
What do you think about that?