为什么我的 bean 为空?
-
25-09-2019 - |
题
我正在尝试学习如何使用 applicationContext。我的目标是在使用单元测试时将模拟数据存储库替换为真实数据存储库。我不想明确地执行此操作,我想通过依赖项注入来执行此操作。
因此,在让事情变得复杂之前,作为一个简单的测试,我只是尝试从 applicationContext.xml 中获取一个 bean。根据我的阅读,这应该有效:
@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {
@Resource
CompanyResult resultBean;
@Test
public void shouldAddResults() {
assertEquals(resultBean.getCompanyName(), "Microsoft");
但我的 resultBean 始终为空。这是我的 applicationContext.xml,位于 WebContent/WEB-INF 下:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="resultBean" name="resultBean" class="com.trgr.cobalt.company.domain.CompanyResult">
<property name="companyName">
<value>Microsoft</value>
</property>
</bean>
</beans>
那么为什么我的resultBean总是为空呢?我做错了什么?
解决方案
你缺少一个 @RunWith(SpringJUnit4ClassRunner.class)
注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {
@Resource
CompanyResult resultBean;
@Test
public void shouldAddResults() {
assertEquals(resultBean.getCompanyName(), "Microsoft");
}
}
顺便提一句, ,在你的样本中, WebContent/WEB-INF
不是合适的位置 applicationContext.xml
.
如果您指定 @ContextConfiguration(locations = "/applicationContext.xml")
那么Spring会寻找 applicationContext.xml
在类路径的根部,而不是在 WebContent/WEB-INF
(jUnit 100% 不知道这是一个 Web 应用程序)。
了解更多信息, , 看 Spring参考文档.
不隶属于 StackOverflow