2011-01-14 10 views
7

में काम नहीं कर रहा है मुझे यकीन है कि मुझे कुछ आसान याद आ रहा है। बार जूनिट टेस्ट में बार आ जाता है, लेकिन फू के अंदर बार क्यों नहीं आ जाता है?Autowire जूनिट परीक्षण

@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

आपका मतलब क्या है, "फू के अंदर बार"? – skaffman

उत्तर

12

फू एक प्रबंधित वसंत बीन नहीं है, आप इसे स्वयं तुरंत कर रहे हैं। तो वसंत आपके लिए अपनी किसी भी निर्भरता को स्वचालित करने वाला नहीं है।

+2

हे। ओह आदमी, मुझे सोने की ज़रूरत है। यह इतना स्पष्ट है। धन्यवाद! – Upgradingdave

7

आप बस फू का एक नया उदाहरण बना रहे हैं। उस उदाहरण को स्प्रिंग निर्भरता इंजेक्शन कंटेनर के बारे में कोई जानकारी नहीं है। आपको अपने परीक्षण में foo autowire करना होगा:

@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

संबंधित मुद्दे