sipXconfig
Tuesday, March 01, 2005
 
autowire mode for spring beans and unit testing
I was playing with several ways of setting up 2 slightly different Spring application context. One for Unit testing, another for real application. I guess classical way of doing it is to split bean factory xml into 3 parts - one that is common, the second that is used in unit test only, and the third one used in application only.
However in some cases when application context for unit test can be a subset of real application context, one can use autowire trick. Setting bean autowire attribute to byType will cause Spring to locate the singletons of a given type to initialize bean properties automatically. If there is more than one candidate Spring will complain. However if there are none, no error is reported and the property remains uninitialized.
We could employ this trick by defining "application only" beans (for example beans than need JNDI) in a separate file and include this file only in real application context. Unit test application context will not find it and as a result some bean properties in common files remain unset (null). You can either mock them, or ignore the fact that they are null if they are not needed.
I have some misgivings about using autowire mode in general, but something has to be said about more concise bean definition. For example one does not have to explicitly initialize hibernate session in each DAO.

Comments:
1.) been there, done that, ok w/doing it again.
2.) in the case of velocity for unitests I wrote a helper that created a velocity engine, no spring. To me, spring helps get functionality into the bowels of your code w/o singletons or passing references around. Unittest do not suffer from this requirement. I think it's a bonus that spring also makes configuring dependencies easier.
 
Post a Comment

<< Home

Powered by Blogger