2011-01-14 9 views
7

Ich bin sicher, ich vermisse etwas Einfaches. Bar wird im Junit-Test autowired, aber warum wird nicht innerhalb von foo autowired?Autowire funktioniert nicht in Junit Test

@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

Was meinst du, "bar inside foo"? – skaffman

Antwort

12

Foo ist nicht ein verwaltetes Frühling Bohne, werden Sie es selbst instanziieren. Also wird Spring keine Abhängigkeiten für dich autowire machen.

+2

heh. Oh Mann, ich brauche Schlaf. das ist so offensichtlich. Vielen Dank! – Upgradingdave

7

Sie erstellen gerade eine neue Instanz von Foo. Diese Instanz hat keine Idee über den Spring-Abhängigkeitsinjektionscontainer. Sie müssen foo in Ihrem Test automatisch feuern:

@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

macht Sinn, vielen Dank! – Upgradingdave