java Autowire 在junit 测试中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4694220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:33:45  来源:igfitidea点击:

Autowire not working in junit test

javaspringjunitjunit4

提问by Upgradingdave

I'm sure I'm missing something simple. bar gets autowired in the junit test, but why doesn't bar inside foo get autowired?

我确定我错过了一些简单的东西。bar 在 junit 测试中自动装配,但为什么 foo 内的 bar 没有自动装配?

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

回答by Nathan Hughes

Foo isn't a managed spring bean, you are instantiating it yourself. So Spring's not going to autowire any of its dependencies for you.

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

回答by Daff

You are just creating a new instance of Foo. That instance has no idea about the Spring dependency injection container. You have to autowire foo in your test:

您只是在创建 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());
    }
}