2011-04-03 106 views
8

我剛剛配置的屬性佔位符在我的Spring配置Spring的屬性佔位符不使用JUnit測試工作

<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中提供默認屬性來覆蓋位置。還有其他解決方案嗎?或者,我是唯一有這個問題的人嗎?

我的測試類看起來有點像這樣:

@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測試了這個。

我引用了包含@PropertySource註釋的Java Config類,而不是在我的@ContextConfiguration中使用XML文件。

@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配置中定義的bean。因此我不得不將WebServiceConfig.class添加到測試類的ContextConfiguration。

+0

classpath *:config.properties怎麼樣? – 2011-04-04 01:04:22

+0

我在測試中使用propertyPlaceholder時沒有問題。問題描述中必須缺少一些東西。嘗試啓用org.springframework的INFO日誌記錄,它顯示加載的上下文文件和屬性文件。 – mrembisz 2011-04-04 07:54:03

+0

我試過classpath *,但是這在測試中似乎不起作用。它只是使用0個資源設置資源數組。我還將日誌記錄設置爲調試,並沒有說它會像啓動應用程序時那樣加載屬性文件。 – suicide 2011-04-04 20:52:25

回答

1

在哪個文件夾中找到config.properties?如果你遵循標準的maven文件夾結構,它應該在src/main/resources/config/config.properties

+0

是的,這就是文件夾 – suicide 2011-04-04 20:27:32

2

我想如果它是一個Maven項目,那麼屬性文件應該在src/test/resource/config文件夾中。因爲在運行測試用例時,測試的類路徑是src/test/resource/config。 嘗試將配置文件放在測試用例類路徑中