Autowire不在junit测试中工作

时间:2011-01-14 17:52:21

标签: java spring junit junit4

我确定我错过了一些简单的事情。 bar在junit测试中获得自动装配,但为什么不在foo内部进行自动装配?

@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());
    }
}

2 个答案:

答案 0 :(得分:12)

Foo不是托管的spring bean,你自己实例化它。因此,Spring不会为您自动装配任何依赖项。

答案 1 :(得分: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());
    }
}