情况:我有@Service注释的服务实现类,可以访问属性文件.
@Service("myService")
public class MySystemServiceImpl implements SystemService{
@Resource
private Properties appProperties;
}
Run Code Online (Sandbox Code Playgroud)
属性对象通过config-file配置.applicationContext.xml中
<util:properties id="appProperties" location="classpath:application.properties"/>
Run Code Online (Sandbox Code Playgroud)
我想测试一下这种实现的方法.
问题:如何从测试类访问MySystemServiceImpl-object,以便正确初始化Properties appProperties?
public class MySystemServiceImplTest {
//HOW TO INITIALIZE PROPERLY THROUGH SPRING?
MySystemServiceImpl testSubject;
@Test
public void methodToTest(){
Assert.assertNotNull(testSubject.methodToTest());
}
}
Run Code Online (Sandbox Code Playgroud)
我不能简单地创建新的MySystemServiceImpl - 比使用appProperties的方法抛出NullPointerException.而且我不能直接在对象中注入属性 - 没有合适的setter方法.
只需在此处输入正确的步骤(感谢@NimChimpsky的回答):
我在test/resources目录下复制了application.properties.
我在test/resources目录下复制了applicationContext.xml.在应用程序上下文中,我添加了新的bean(应用程序属性的定义已经在这里):
<bean id="testSubject" class="com.package.MySystemServiceImpl">
Run Code Online (Sandbox Code Playgroud)我用这样的方式修改了测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
public class MySystemServiceImplTest {
@Autowired
MySystemServiceImpl testSubject;
}
Run Code Online (Sandbox Code Playgroud)这就是诀窍 - 现在在我的测试类中可以使用全功能对象
或者,为了进行集成测试,我这样做.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext-test.xml"})
@Transactional
public class MyTest {
@Resource(name="myService")
public IMyService myService;
Run Code Online (Sandbox Code Playgroud)
然后像平常一样使用该服务.将应用程序上下文添加到test/resources目录
| 归档时间: |
|
| 查看次数: |
8977 次 |
| 最近记录: |