2011-01-14 9 views
7

Jestem pewien, że brakuje mi czegoś prostego. pasek zostaje autowired w teście na junit, ale dlaczego pasek wewnątrz foo nie zostanie automatycznie wykasowany?Autowire nie działa w junitowym teście

@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

Co masz na myśli mówiąc "bar inside foo"? – skaffman

Odpowiedz

12

Foo nie jest zarządzanym wiosennym komponentem, sam go tworzysz. Więc Spring nie będzie dla ciebie autorstwa żadnej z jego zależności.

+2

heh. och człowieku, potrzebuję snu. to takie oczywiste. dzięki! – Upgradingdave

7

Po prostu tworzysz nową instancję Foo. Ta instancja nie ma pojęcia o pojemniku iniekcyjnym zależnym od wiosny. Musisz przetestować foo w teście:

@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

ma sens, dzięki bardzo! – Upgradingdave

Powiązane problemy