【问题标题】:Autowire not working in junit testAutowire在junit测试中不起作用
【发布时间】:2011-01-14 17:52:21
【问题描述】:

我确定我错过了一些简单的东西。 bar 在 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());
    }
}

【问题讨论】:

  • 你是什么意思,“酒吧里面 foo”?

标签: java spring junit junit4


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你只是在创建一个新的 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());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 2012-05-29
      • 2017-12-20
      • 2012-02-07
      • 1970-01-01
      相关资源
      最近更新 更多