Upg*_*ave 7 java junit spring junit4
我确定我错过了一些简单的事情.bar在junit测试中获得自动装配,但为什么不在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());
}
}
Run Code Online (Sandbox Code Playgroud)
您只是在创建一个新的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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11321 次 |
| 最近记录: |