2011-01-14 4 views
7

Уверен, что мне не хватает чего-то простого. bar получает autwired в junit-тесте, но почему не запрещается внутри foo получить autwired?Autowire не работает в 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

Что вы подразумеваете под «bar inside foo»? – skaffman

ответ

12

Foo не управляемый весенний боб, вы создаете его сами. Поэтому Spring не собирается авторизовать ни одну из своих зависимостей для вас.

+2

heh. о человеке, мне нужно спать. это так очевидно. благодаря! – Upgradingdave

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