2011-09-05 113 views
5

我想我的類路徑設置遇到了錯誤。在Junit測試中使用來自WEB-INF的i18n資源

我想測試一個國際化的網絡應用程序,它具有像這樣定義的MessageSource的:

<bean id="messageSource" 
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
    <property name="basenames"> 
     <list> 
      <value>/WEB-INF/i18n/errors</value> 
      <value>/WEB-INF/i18n/messages</value> 
      <value>/WEB-INF/i18n/links</value> 
      <value>/WEB-INF/i18n/forms</value> 
      <value>/WEB-INF/i18n/communication</value> 
     </list> 
    </property> 
</bean> 

裝載這些數值完全在生產環境中。 但是,運行Junit測試時,它不能解析這些屬性文件,因爲它們不在類路徑中。

不過,我想他們是不是在classpath中,因爲這樣我可以利用該功能,我可以更改屬性文件的東西,它反映立即在網站上:Since application servers typically cache all files loaded from the classpath, it is necessary to store resources somewhere else (for example, in the "WEB-INF" directory of a web app). Otherwise changes of files in the classpath will not be reflected in the application.

Spring的ApplicationContext是位於有:/src/main/resources/spring/applicationContext.xml 並裝入JUnit測試這些註釋:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"}) 

我怎樣才能得到JUnit來拿起這些非類路徑的資源呢? 屬性文件在/src/main/webapp/WEB-INF/i18n/*

Junit:4.7。

Spring:3.0.5。

回答

6

我在此期間解決了我最初的問題。

馬修的解決方案並沒有幫助我 - 仍然非常好的投入。 他不知道我在項目中使用maven,因爲我從來沒有告訴過。

然而,行家內,我發現了一個解決我的問題:

 <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-surefire-plugin</artifactId> 
      <configuration> 
       <skipTests>true</skipTests> 
       <additionalClasspathElements> 
        <additionalClasspathElement>src\main\webapp\</additionalClasspathElement> 
       </additionalClasspathElements> 
      </configuration> 
     </plugin> 

我配置的萬無一失-插件在類路徑拾取的附加元件。

3

在我看來,最簡單的解決方案是隻使用你當JUnit是執行重寫一個屬性:

<bean id="messageSource" 
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
    <property name="basenames"> 
     <list> 
      <value>${path.prefix}/WEB-INF/i18n/errors</value> 
      <value>${path.prefix}/WEB-INF/i18n/messages</value> 
      <value>${path.prefix}/WEB-INF/i18n/links</value> 
      <value>${path.prefix}/WEB-INF/i18n/forms</value> 
      <value>${path.prefix}/WEB-INF/i18n/communication</value> 
     </list> 
    </property> 
</bean> 

您在PropertyPlaceholderConfigurer

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 
    <property name="properties"> 
     <props> 
      <prop key="path.prefix"></prop> <!-- empty --> 
     </props> 
    </property> 
</bean> 

這propertyConfigurer此設置的默認值bean定義需要在messageSource bean定義之前。在JUnit測試,您可以:

  1. 設置的屬性,通過使用不同版本的propertyConfigurer具體到您的測試或
  2. 通過命令行或系統上-Doption設置的系統屬性。請在您的@Before中設置setProperty(「path.prefix」,「src/main/webapp」)。

請注意,如果你這樣做(2),那麼Spring有時緩存系統屬性的值,這樣你就無法再更改系統屬性。它使用原始值。