Search code examples
springunit-testingspring-junit

Unit Test with Spring JPA - @Autowired is not working


I have a unit test and a helper class. Unfortunely the Helper class' autowire does not work. It works fine in MyTest class.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath*:context.xml"})
    @Component
    public class MyTest {

        @Autowired
        private Something something1;

        @Autowired
        private Something something2;
        ..

        @Test
        public void test1()
        {
            // something1 and something2 are fine
            new Helper().initDB();
            ..
        }
   }

// Same package
public class Helper {
   @Autowired
   private Something something1;

   @Autowired
   private Something something2;
   ..

   public void initDB()
    {
        // something1 and something2 are null. I have tried various annotations.
    }
}

I'd like to avoid using setters because I have like 10 of those objects and different tests have different ones. So what is required to get @Autowired working in Helper class? Thx!


Solution

  • You must not create the Helper class by a new statement, but you have to let spring create it to become a spring been and therefore its @Autowired fields get injected.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath*:context.xml"})
    @Component
    public class MyTest {
    
        @Autowired
        private Something something1;
    
        @Autowired
        private Something something2;
        ..
    
        @Autowired
        private Helper helper
    
        @Test
        public void test1() {
            helper.initDB();
        }
    }
    
    
    //this class must been found by springs component scann
    @Service
    public class Helper {
       @Autowired
       private Something something1;
    
       @Autowired
       private Something something2;
    
       public void initDB(){...}
    }