Search code examples
springintegration-testingautowiredapplicationcontexttest-framework

Autowiring in Spring Testcontext framework


I have a integration test which does the following:

@ContextConfiguration( locations={..path to xmls..} )
class IntegTestBase{

   --- some field initializations; ---
}

class MyIntegTest extends IntegTestBase{

   @Test
   public testingMethod(){
      MyClass obj = new MyClass();
      obj.methodToBeTested();

      ---- some assertions ----
   }
}

class MyClass{

   @Autowired
   Something obj1;

   public int methodToBeTested(){

      --- Somecode ---
   }
}

In the above code i thought, when the testcase runs the MyClass object will the created and all the fields will be autowired. But what happened was all the autowired fields were null when the tests were run. It did not complain about not able to find the bean definition, so i assume the test context is visible to here. but i dont understand why it is not wiring.

On the otherhand, I am able to create those fields in the testclass autowire them and set it to the created objects. Can someone tell why the fields are null?


Solution

  • You are creating Spring bean using new operator:

    MyClass obj = new MyClass();
    

    this almost never works1. You need to ask Spring container to provide fully operational, initialized instance of MyClass bean, e.g. with autowiring/DI inside your test case:

    @ContextConfiguration( locations={..path to xmls..} )
    class IntegTestBase{
    
      @Autowired
      protected MyClass obj;
    
    }
    

    Later in your test simply use it:

    @Test
    public testingMethod(){
      //don't recreate `obj` here!
      obj.methodToBeTested();
    
      ---- some assertions ----
    }
    

    In fact this is the functionality that Spring Test Support provides. You must also remember that obj will point to the exact same instance in every test if MyClass is a singleton, but that's typically not a problem.

    1 theoretically possible with full AspectJ, but you don't want to go that path.