Autowire不在junit测试中工作

Upg*_*ave 7 java junit spring 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*hes 12

Foo不是一个托管的spring bean,你自己实例化它.因此,Spring不会为您自动连接任何依赖项.

  • 嘿嘿.哦,伙计,我需要睡觉.那是显而易见的.谢谢! (2认同)

Daf*_*aff 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());
    }
}
Run Code Online (Sandbox Code Playgroud)