我使用了 JUnit,但有些测试存在一些问题,这些测试在 Spring bean 内有 @Autowired 注释,当我引用它们时,@Autowired 的 bean 始终为 NULL。
这是示例代码:
public class Test {
protected ApplicationContext ac;
@Before
public void setUp() {
ac = new FileSystemXmlApplicationContext("classpath:config/applicationContext.xml"
"classpath:config/test-datasources.xml");
}
@Test
public void testRun() throws Exception {
IManager manager = (IManager)this.ac.getBean("manager");
manager.doSomething();
}
}
@Service
public class Manager implements IManager {
public boolean doSomething() throws Exception {
ParametersJCSCache parametersJCSCache = new ParametersJCSCache();
String paramValue = parametersJCSCache.getParameter("XPTO");
...
}
}
public class ParametersJCSCache extends SpringBeanAutowiringSupport {
@Autowired
private IParameterManager parameterManager; //THIS IS NULL
}
当调用 Manager 对象时,Spring 生成代理,但是当访问 @AutowiredparameterManager 时,该对象为 null,并且由于这个问题,我无法测试此方法。
知道是什么原因造成的吗?为什么对象没有被注入?它在 Web 应用程序的上下文中运行良好,但在测试上下文中始终为 NULL。
尝试使用 spring runner 来运行单元测试。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/applicationContext.xml",
"classpath:config/test-datasources.xml"})
public class MyTest {
@Autowired private IManager manager;
@Test public void someTest() {
assertNotNull(manager);
}
}
它只会在需要时加载配置一次,并且会自动装配您的 junit 类
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)