情况:我有使用@Service注释的服务实现类,可以访问属性文件。
@Service("myService")
public class MySystemServiceImpl implements SystemService{
@Resource
private Properties appProperties;
}
属性对象是通过config-file配置的。applicationContext.xml
<util:properties id="appProperties" location="classpath:application.properties"/>
我想测试此实现的一些方法。
问题:如何通过测试类访问MySystemServiceImpl-object,从而正确初始化Properties appProperties?
public class MySystemServiceImplTest {
//HOW TO INITIALIZE PROPERLY THROUGH SPRING?
MySystemServiceImpl testSubject;
@Test
public void methodToTest(){
Assert.assertNotNull(testSubject.methodToTest());
}
}
我不能简单地创建新的MySystemServiceImpl-比使用appProperties的方法会抛出NullPointerException。而且我无法直接在对象中插入属性-没有适当的设置方法。
只需在此处输入正确的步骤即可(感谢@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;
}
这很容易-现在在我的测试类中,可以使用功能齐全的对象
或者,要进行集成测试。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext-test.xml"})
@Transactional
public class MyTest {
@Resource(name="myService")
public IMyService myService;
然后像往常一样使用该服务。将应用程序上下文添加到您的test / resources目录中
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句