情况:我有服务实现类,可以使用@Service注释并可以访问属性文件。如何从jUnit访问Spring @Service对象测试
@Service("myService")
public class MySystemServiceImpl implements SystemService{
@Resource
private Properties appProperties;
}
属性对象通过配置文件进行配置。 的applicationContext.xml
<util:properties id="appProperties" location="classpath:application.properties"/>
我想测试这个实现的一些方法。
问题:如何从测试类访问MySystemServiceImpl对象,使属性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的答案):
我复制测试/资源目录application.properties。
我复制了applicationContext.xml under test/resources dir。在应用方面,我添加新豆(应用程序属性的定义是已经在这里):
<bean id="testSubject" class="com.package.MySystemServiceImpl">
我修改测试类以这样一种方式:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/applicationContext.xml"}) public class MySystemServiceImplTest { @Autowired MySystemServiceImpl testSubject; }
这使的伎俩 - 现在我的测试类的功能齐全的对象可用
谢谢,它有很大的帮助。 – dim1902