Auto wiring Spring Test Cases

Feb 8th, 2008 | By | Category: java

Spring is of late being used universally. Hence the need arises to either

  • Test Spring wiring.
  • Write test cases that are best wired using Spring due to the complexity of the wiring of the objects involved.

For instance,let us consider a test case that tests a service which in turn utilizes a Dao that in turn uses a datasource. Due to the complexity of the wiring, it is much easier to do all this using Spring. The test case then has to instantiate spring and initialize the “service” from it.

Hence the typical code that has to get written would be something like

  1. public class MyTestCase extends TestCase {
  3. protected Service service;
  4. public void setUp(){
  5. // initialize spring bean factory from a spring configuration file.
  6. service = (Service) beanFactory.getBean("service");
  7. }
  8. }

This code gets repetitive across tests thereby making us wish if we could do something for re-use.

Here is a simple SpringJUnitTestBase class which does exactly that.
The code now becomes the following:

  1. public class MyTestCase extends SpringJUnitTestBase {
  2. // This will get auto-wired by name.
  3. protected Service service;
  4. public void setService(Service s){
  5. service = s;
  6. }
  8. public void setUp(){
  9. }
  10. }

Far simpler huh?? The only caveat is that the spring file should have the exact same name and be in the same package as the test case. So in this case we need to have MyTestCase.xml in the same package.

Be Sociable, Share!

 Raja has been blogging in this forum since 2006. He loves a technical discussion any day. He finds life incomplete without a handy whiteboard and a marker.

Tags: , ,

Leave Comment