情况:我有一个用@Service 注释的服务实现类,可以访问属性文件。
@Service("myService")
public class MySystemServiceImpl implements SystemService{
@Resource
private Properties appProperties;
}
属性对象是通过配置文件配置的。 applicationContext.xml
<util:properties id="appProperties" location="classpath:application.properties"/>
我想测试这个实现的一些方法。
问题:如何以正确初始化属性 appProperties 的方式从测试类访问 MySystemServiceImpl 对象?
public class MySystemServiceImplTest {
//HOW TO INITIALIZE PROPERLY THROUGH SPRING?
MySystemServiceImpl testSubject;
@Test
public void methodToTest(){
Assert.assertNotNull(testSubject.methodToTest());
}
}
我不能简单地创建新的 MySystemServiceImpl - 因为使用 appProperties 的方法会抛出 NullPointerException。而且我不能直接在对象中注入(inject)属性 - 没有合适的 setter 方法。
只需在此处输入正确的步骤(感谢@NimChimpsky 的回答):
我将 application.properties 复制到 test/resources 目录下。
我将 applicationContext.xml 复制到 test/resources 目录下。在应用程序上下文中,我添加了新 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;
然后像往常一样使用该服务。将应用程序上下文添加到您的测试/资源目录
关于java - 如何从 jUnit 测试访问 Spring @Service 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7723951/