Spring Testing Survival guide

If you have an application with thousand of beans, you must do unit testing but…Spring testing is boring, belive me.
A very complex Spring application usually have a lot of dependency: I had to manage over 3000 beans definitions in a production project right now.
Sometimes you want only to test a bit of it, and setting up a complete Spring Context will drive you crazy.
To avoid losing mind, my suggestion is to …cheat. Let’see how.
The trick is to break dependency where you does not need them: simply push some null pointer to Spring.
In the following example, if a SillyClass need a ComplexManager, it will be happy with our null pointer:
[java]
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("minimal-test-config.xml")
@PropertySource("classpath:spring/myconfig.properties")
@Configuration
public class CheatingTestTest extends AbstractTransactionalJUnit4SpringContextTests {
….
@Bean(name="ComplexManager")
public static ComplexManager getCheaterManager(){ return null;}
….
}
[/java]
As long as the test did not requires SillyClass to use ComplexManager, you are safe.
The right bunch of ‘Null Beans’ can save you from wiring a tons of dependencies.
The ‘static’ is not required, but I like it.

For generic interfaces, you can try to solve your trouble returning a dummy inner class, with hacked methods to break dependency resolution.

The second trick is to use a bit more the annotation

1

@Autowired(required=false)

to prevent useless dependencies. This trick change the implementation requirements, so use it savy.

Finally you can speed up things defining wrapping all the test beans in a lazy configuration, overriding it when needed:
[code lang=”java” highlight=”2,6″]
@Configuration
@Lazy(true)
public class DummyDollConfiguration {

@Bean(name="DummyDoll")
@Lazy(false)
public static Object getDummyDoll() {
System.err.println("The Doll House is Open!");
return new Object();
}
….
}
[/code]
Here we want to see ‘The Doll House is Open!’ message in a Eclipse console, but we want to avoid to create all the test beans if we does not need it. So the lazy directive save our day.
A correct Layering of Object interfaces will greatly improve this tricks.