【发布时间】:2011-10-11 09:31:16
【问题描述】:
情况:我有使用 @Service 注释的服务实现类,可以访问属性文件。
@Service("myService")
public class MySystemServiceImpl implements SystemService{
@Resource
private Properties appProperties;
}
属性对象是通过配置文件配置的。 applicationContext.xml
<util:properties id="appProperties" location="classpath:application.properties"/>
我想测试一下这个实现的一些方法。
问题:如何从测试类中访问 MySystemServiceImpl-object 以使属性 appProperties 正确初始化?
public class MySystemServiceImplTest {
//HOW TO INITIALIZE PROPERLY THROUGH SPRING?
MySystemServiceImpl testSubject;
@Test
public void methodToTest(){
Assert.assertNotNull(testSubject.methodToTest());
}
}
我不能简单地创建新的 MySystemServiceImpl - 使用 appProperties 的方法会引发 NullPointerException。而且我不能直接在对象中注入属性 - 没有合适的 setter 方法。
只需在此处输入正确的步骤(感谢@NimChimpsky 的回答):
我在 test/resources 目录下复制了 application.properties。
-
我在 test/resources 目录下复制了 applicationContext.xml。在应用程序上下文中,我添加了新的 bean(应用程序属性的定义已经在这里):
<bean id="testSubject" class="com.package.MySystemServiceImpl"> -
我以这种方式修改了测试类:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/applicationContext.xml"}) public class MySystemServiceImplTest { @Autowired MySystemServiceImpl testSubject; } 这就是诀窍 - 现在在我的测试类中,功能齐全的对象可用
【问题讨论】: