Spring的Property Placeholder不适用于jUnit测试

sui*_*ide 8 spring unit-testing properties

我刚刚在Spring配置中配置了一个属性占位符

<context:property-placeholder location="classpath:/config/config.properties" />
Run Code Online (Sandbox Code Playgroud)

如果我使用此配置运行应用程序一切正常.但是,如果我尝试运行单元测试,则测试无法加载,ApplicationContext因为a FileNotFoundException.如果我尝试从Eclipse运行测试以及通过maven运行测试时会发生这种情况.

我也尝试PropertyPlaceholderConfigurer直接配置相同的结果.

看起来文件不在类路径位置,即使测试类是用注释的

 @ContextConfiguration("classpath:/config/spring-config.xml")
Run Code Online (Sandbox Code Playgroud)

这些文件位于同一文件夹中,它会找到xml配置.

我已经尝试使用不同的路径:classpath:config/config.properties没有classpath前缀,都没有用.文件前缀的绝对路径有效,但这不是一个好的解决方案.

有没有办法让属性占位符与测试一起工作?我已经找到的一个解决方案是通过在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);
}
Run Code Online (Sandbox Code Playgroud)

上下文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>
Run Code Online (Sandbox Code Playgroud)

我终于找到了解决方案/解决方法

看起来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 {
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是webservices.xml还包含WebServiceConfig类的bean定义.但是,Spring无法找到Java Config中定义的bean.因此,我不得不将WebServiceConfig.class添加到测试类的ContextConfiguration中.

gka*_*mal 1

config.properties 位于哪个文件夹中?如果您遵循标准的 maven 文件夹结构,它应该位于 src/main/resources/config/config.properties 中