【发布时间】:2011-07-28 19:19:45
【问题描述】:
我刚刚在我的 Spring 配置中配置了一个属性占位符
<context:property-placeholder location="classpath:/config/config.properties" />
如果我使用此配置运行应用程序,一切正常。但是,如果我尝试运行单元测试,由于FileNotFoundException,测试无法加载ApplicationContext。如果我尝试从 Eclipse 运行测试以及通过 maven 运行测试,就会发生这种情况。
我也尝试直接配置PropertyPlaceholderConfigurer,结果相同。
看起来文件不在类路径位置,即使测试类被注释了
@ContextConfiguration("classpath:/config/spring-config.xml")
文件在同一个文件夹中,它会找到 xml 配置。
我已经尝试使用不同的路径:classpath:config/config.properties 并且没有类路径前缀,都无法正常工作。带有文件前缀的绝对路径有效,但这不是一个好的解决方案。
有没有办法让属性占位符与测试一起使用?我已经找到的一种解决方案是通过在 xml.xml 中提供默认属性来覆盖该位置。还有其他解决方案吗?还是只有我一个人有这个问题?
我的测试类看起来像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/config/spring-config.xml")
@Transactional
public class JpaImageDaoTest {
@Autowired
private ImageDataDao imageDataDao;
@Test
public void testFindById() {
Image anImage = new Image();
anImage.setData(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 });
imageDao.save(anImage);
Image image = imageDao.findById(imageData.getId());
assertNotNull(image);
assertEquals(anImage, image);
}
上下文 xml 如下所示:
<context:property-placeholder location="classpath:/config/config.properties" />
<bean id="imageScalingService" class="service.image.ImageScalingService">
<property name="maxWidth" value="${scaling.thumbnail.maxWidth}" />
<property name="maxHeight" value="${scaling.thumbnail.maxHeight}" />
</bean>
我终于找到了解决方案/解决方法
似乎 Spring 不喜欢混淆 XML 和 Java Config,或者至少在这种情况下它不起作用。我用 4.0.9 对此进行了测试。
我没有在 @ContextConfiguration 中使用 XML 文件,而是引用了一个包含 @PropertySource 注释的 Java Config 类。
@Configuration
@PropertySource("test.properties")
@ImportResource("webservices.xml")
public class TestPlaceholderConfig {
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestPlaceholderConfig.class, WebServiceConfig.class})
public class MyTest {
}
奇怪的是 webservices.xml 还包含 WebServiceConfig 类的 bean 定义。但是,Spring 无法找到 Java Config 中定义的 bean。因此我不得不将 WebServiceConfig.class 添加到测试类的 ContextConfiguration 中。
【问题讨论】:
-
classpath*:config.properties 怎么样?
-
我在测试中使用 propertyPlaceholder 没有问题。您的问题描述中一定缺少某些内容。尝试为 org.springframework 启用 INFO 日志记录,它会显示加载的上下文文件和属性文件。
-
我尝试了 classpath* 但这似乎在测试中也不起作用。它只是设置了一个包含 0 个资源的资源数组。我还将日志记录设置为调试,它并没有说它会像启动应用程序时那样加载属性文件。
-
你能给我看一下 sn-p TestClass 和 spring 上下文文件吗?
-
@adisembiring 我更新了问题,希望够了
标签: unit-testing spring properties