2012-02-02 114 views
4

我寫了一個JUnit測試,用於驗證服務針對其XSD返回的xml。我最初把XSD放在src/main/resrouces/xsd/<filename>.xsd下但現在我需要將它作爲靜態資源在webapp之下移動,以便在部署應用程序時公開訪問它。如何從JUnit測試中訪問webapp下的靜態資源?

我寧願沒有兩個副本,因爲我希望有人遲早會修改錯誤的。

我當時正在加載文件getClass().getResource("/xsd/<filename>.xsd"),如果資源移動到webapp下,我將如何訪問它?

回答

3

在你的pom中添加它作爲資源目錄。

<resources> 
    <resource> 
     <directory>src/main/resources</directory> 
    </resource> 
    <resource> 
     <directory>src/main/webapp</directory> 
     <includes> 
      <include>xsd/schema.xsd</include> 
     </includes> 
    </resource> 
</resources> 

在java中使用

String path = "/xsd/schema.xsd"; 
InputStream is = getClass().getResourceAsStream(path); 
+0

我沒有測試過這一點,因爲我去了另一條路線,最終,但我想它會奏效。 – 2012-03-18 00:23:36

0

你的資源仍將保留在類路徑中,因此通常加載它你現在要做的應該保持工作的方式。

3

/src/main/webapp內容放置在CLASSPATH創建WAR時和部署,而不是在JUnit測試(無論是在Maven的,在我的IDE)。您必須明確使用它們:

new File("src/main/webapp/xsd/<filename>.xsd"); 

只要項目主目錄是運行測試時的當前目錄,就應該這樣工作。悲傷但真實。