Upgradingdave
Upgradingdave

Reputation: 13066

Autowire not working in junit test

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

Upvotes: 8

Views: 13004

Answers (2)

Daff
Daff

Reputation: 44215

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

Upvotes: 8

Nathan Hughes
Nathan Hughes

Reputation: 96394

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.

Upvotes: 13

Related Questions