2011-01-14 85 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