@Autowired与JUnit测试 [英] @Autowired with JUnit tests
问题描述
我已经使用了JUnit,但是某些测试存在一些问题,这些测试在Spring bean中具有@Autowired批注,而当我引用它们时,@ Autowired的bean始终为NULL.
I´ve using JUnit but some tests have some issues, these tests have @Autowired annotation inside the Spring beans and when i reference them the beans that are @Autowired were always 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会生成代理,但是当访问@Autowired parameterManager时,该对象为null,因此,我无法测试此方法.
When invoking the Manager object the Spring generates the proxy but when accessing the @Autowired parameterManager the object is null, and with this issue i can´t test this method.
有人知道是什么原因造成的吗?为什么没有注入物体?它可以在Web应用程序的上下文中很好地工作,但是在测试上下文中始终为NULL.
Any idea what is causing this? Why does the object not get injected? It works well in the context of a web application, but in the test context is always NULL.
推荐答案
我终于找到了解决我问题的方法. 查找此帖子 SpringBeanAutowiringSupport不会在jUnit测试中注入bean ,做这样的事情,JUnit测试就可以了.
I've finally found a solution to my problem. Find this post SpringBeanAutowiringSupport does not inject beans in jUnit tests and do something like this the JUnit tests works.
这篇关于@Autowired与JUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!