2011-01-14 73 views
7

我敢肯定我错过了一些简单的东西。 bar在junit测试中被自动装入,但为什么不在foo里面自动装入?Autowire不在junit测试

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration({"beans.xml"}) 
public class BarTest { 

    @Autowired 
    Object bar; 

    @Test 
    public void testBar() throws Exception { 
      //this works 
     assertEquals("expected", bar.someMethod()); 
      //this doesn't work, because the bar object inside foo isn't autowired? 
     Foo foo = new Foo(); 
     assertEquals("expected", foo.someMethodThatUsesBar()); 
    } 
} 
+0

你是什么意思,“bar inside foo”? – skaffman 2011-01-14 17:54:06

回答

12

Foo不是托管的spring bean,你自己实例化它。所以Spring不会为你自动装载它的任何依赖项。

+2

heh。哦,我需要睡觉。这很明显。谢谢! – Upgradingdave 2011-01-14 18:00:11

7

您正在创建Foo的新实例。该实例不知道Spring依赖注入容器。你必须在你的测试中自动装配foo:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration({"beans.xml"}) 
public class BarTest { 

    @Autowired 
    // By the way, the by type autowire won't work properly here if you have 
    // more instances of one type. If you named them in your Spring 
    // configuration use @Resource instead 
    @Resource(name = "mybarobject") 
    Object bar; 
    @Autowired 
    Foo foo; 

    @Test 
    public void testBar() throws Exception { 
      //this works 
     assertEquals("expected", bar.someMethod()); 
      //this doesn't work, because the bar object inside foo isn't autowired? 
     assertEquals("expected", foo.someMethodThatUsesBar()); 
    } 
} 
+0

非常有意义,非常感谢! – Upgradingdave 2011-01-14 18:06:37