2011-01-14 35 views
7

Tôi chắc chắn rằng tôi thiếu một cái gì đó đơn giản. thanh được autowired trong thử nghiệm junit, nhưng tại sao không thanh bên trong foo nhận autowired?Autowire không hoạt động trong thử nghiệm 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

Ý của bạn là "bar inside foo"? – skaffman

Trả lời

12

Foo không phải là đậu mùa xuân được quản lý, bạn đang tự khởi tạo nó. Vì vậy, mùa xuân sẽ không để autowire bất kỳ phụ thuộc của nó cho bạn.

+2

heh. Ôi trời, tôi cần ngủ. điều đó hiển nhiên. cảm ơn! – Upgradingdave

7

Bạn vừa tạo một phiên bản mới của Foo. Ví dụ đó không có ý tưởng về container tiêm phụ thuộc Spring. Bạn phải tự kiểm tra trong thử nghiệm của mình:

@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

có ý nghĩa hoàn hảo, cảm ơn nhiều! – Upgradingdave

Các vấn đề liên quan