2015-11-03 134 views
0

我有单元测试和辅助类。 不幸的是,Helper类的autowire不起作用。 它在MyTest类中正常工作。春季JPA单元测试 - @Autowired无法正常工作

@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. 
    } 
} 

我想避免使用setter,因为我有10个这样的对象,不同的测试有不同的对象。 那么在Helper类中获得@Autowired需要什么?谢谢!

+0

的[为什么我的春节@Autowired场空?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null)可能的复制 – kryger

回答

0

您不能通过new语句创建Helper类,但必须让spring创建它以成为弹簧,因此它的@Autowired字段被注入。

@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(){...} 
} 
+0

真棒: ).... – NoobieNoob

0

你的助手类不是由spring实例化的......你必须添加一个类似@component的注释(如果你使用包扫描),或者你可以在你的springconfiguration类中定义类为Bean。但是如果您自己创建实例,则不起作用