我使用了 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,因此我无法测试此方法。
知道是什么原因造成的吗?为什么对象没有被注入(inject)?它在 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);
}
}
它只会在需要时加载配置一次,并且会 Autowiring 你的 junit 类
关于java - @Autowired 与 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26462926/