开发者

Autowire not working in junit test

开发者 https://www.devze.com 2023-02-05 05:25 出处:网络
I\'m sure I\'m missing something simple. bar gets autowired in the junit test, but why doesn\'t bar inside foo get autowired?

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"beans.xml"})
public class BarTest {  

    @Autowired
    Object bar;

    @Test
    public void testBar() throws Exception {
      开发者_StackOverflow社区      //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());
    }
}


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.


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:

@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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号