Autowire не работает в тесте junit - PullRequest
7 голосов
/ 14 января 2011

Я уверен, что мне не хватает чего-то простого.В тесте junit bar автоматически подключается, но почему внутри 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 ]

12 голосов
/ 14 января 2011

Foo не управляемый боб, вы сами его создаете. Поэтому Spring не собирается автоматически связывать вас своими зависимостями.

7 голосов
/ 14 января 2011

Вы просто создаете новый экземпляр 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());
    }
}
...