2013-10-23 23 views
2

我想用我的java代碼加載'log4j.xml'來運行'mvn test'。我收到文件未找到異常。會很好,得到一些幫助。使用maven測試加載log4j.xml

我的Java代碼:

​​

JUnit測試用例:

import static org.junit.Assert.*; 

import org.junit.Test; 

public class MyClassTests { 

    @Test 
    public void testCheck() { 
     MyClass myc = new MyClass(); 
     assertEquals(true, myc.check()); 
    } 
} 

的pom.xml的塊

<plugin> 
     <groupId>org.apache.maven.plugins</groupId> 
     <artifactId>maven-surefire-plugin</artifactId> 
     <version>2.15</version> 
     <configuration> 
      <includes> 
       <include>**/*Tests.java</include> 
       <include>log4j.xml</include> 
      </includes> 
      <argLine>-Xmx512m</argLine> 
     </configuration> 
     <inherited>true</inherited> 
    </plugin> 

˚F ILE結構:

  • 的pom.xml = */myproject的/ pom.xml的
  • 的log4j.xml = */myproject的/ SRC /主/資源/的log4j.xml
  • myclass.java = */myproject的/src/main/java/MyClass.java
  • JUnit測試= */myproject的/ src目錄/測試/ JAVA/MyClassTests.java

當我運行命令 「MVN測試」,我得到一個文件不發現log4j.xml的例外情況:

java.io.FileNotFoundException: */myproject的/ log4j.xml文件(沒有這樣的文件或目錄 )

基本上代碼正在尋找項目的根文件夾的log4j.xml,而不是/ src/main/resources文件夾。我不想將代碼更改爲「DOMConfigurator.configure(」/ src/main/resources/log4j.xml「);」這將導致部署的應用程序出現問題。需要更優雅的解決方案。

+1

以下代碼解決了該問題。這個問題可以關閉: 'DOMConfigurator.configure(this.getClass()。getClassLoader()。getResource(「log4j.xml」));' – Srik

回答

0

我看不到你的POM,但你應該在你的構建聲明中有一個資源部分,以確保src/main/resources可用作類資源。

<build> 
    <outputDirectory>build/maven/${artifactId}/target/classes</outputDirectory> 

<resources> 

      <resource> 
       <directory>src/main/resources</directory> 
       <includes> 
        <include>**/*.xml</include> 
       </includes> 
      </resource> 
     </resources> 
</build> 

然後,DOMConfigurator應該能夠將log4j.xml定位爲類資源。如果您在項目上運行maven軟件包,則應查看構建目標文件夾或目標文件夾,並查看log4j.xml是否已複製到classes文件夾中。然後你會知道它應該作爲一個資源。

+0

即使現在,log4j.xml也會被複制到目標/類文件夾。儘管你會嘗試你的方法。我想知道是否可以從輸入流加載DOM配置,而不是提供文件名。我正在加載我的配置文件。它工作正常'InputStream config = this.getClass()。getClassLoader()。getResourceAsStream(「config.properties」);'我的配置文件與log4j.xml文件位於同一目錄中。 – Srik

+0

您提出的解決方案無效。我收到了同樣的信息。但是,我能夠使用類加載器來工作。儘管感謝您的幫助。 – Srik