2011-11-30 11 views
2

私は足を疲れさせていますが、それは急な学習曲線です。私はユニットテストの中からプレーンテキストファイルをロードしようとしています。テストは合格しました。プロジェクトをmavenプロジェクトに変換したので、テストファイルがどこにあるのか分からないようです。ユニットテストで使用しているテキストファイルがMavenに表示されません


// I have the following test that I would like to run: 

package net.stevenpeterson.base; 

import static org.junit.Assert.*; 

import net.stevenpeterson.base.LoadStringUtility; 

import org.junit.Test; 

public class LoadStringUtilityTest { 

    @Test 
    public void testSingleLine() { 
     assertEquals("Loading File", "This is a test." , loadFile("singleLine")); 
    } 

    @Test 
    public void testSeveralLines() { 
     assertFalse("Compare a string appended with extra lines, should not compare true. ", "This is a test.".equals(loadFile("severalLines"))); 
    } 

    @Test 
    public void loadSherlockHolmes() { 
     String fileToLoad = "cano.txt"; 
     try{ 
     StringBuilder holmesCanon = LoadStringUtility.LoadString(fileToLoad); 

     System.out.println("Finished Loading file: chars read=" + holmesCanon.length()); 
     assertTrue("loading size of file:", true); 
     }catch(Exception e){ 
     fail("Exception thrown while loading: " + fileToLoad); 
     } 

    } 


    private String loadFile(String fileName) { 
     StringBuilder loadedFromFile = new StringBuilder(); 
     try { 
      loadedFromFile = LoadStringUtility.LoadString(fileName); 
     } catch (Exception e) { 
      fail("Unable to find load file: " + fileName); 
      e.printStackTrace(); 
     } 
     return loadedFromFile.toString(); 
    } 
} 

次の私のpom.xmlファイルである:私はユニットテストを実行すると


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
     <modelVersion>4.0.0</modelVersion> 

     <groupId>net.stevenpeterson</groupId> 
     <artifactId>bookreader</artifactId> 
     <version>1.0-SNAPSHOT</version> 
     <packaging>jar</packaging> 

     <name>bookreader</name> 
     <url>http://maven.apache.org</url> 

     <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     </properties> 

     <dependencies> 
     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.8.1</version> 
      <scope>test</scope> 
     </dependency> 
     </dependencies> 

    <build> 
     <testResources> 
      <testResource> 
      <directory>src/test/resources</directory> 
      </testResource> 
     </testResources> 
    </build> 

    </project> 


[email protected]:~/maven-conversion/bookreader$ mvn test 
[INFO] Scanning for projects... 
[INFO]                   
[INFO] ------------------------------------------------------------------------ 
[INFO] Building bookreader 1.0-SNAPSHOT 
[INFO] ------------------------------------------------------------------------ 
[INFO] 
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ bookreader --- 
[INFO] Using 'UTF-8' encoding to copy filtered resources. 
[INFO] skip non existing resourceDirectory /home/steven/maven-conversion/bookreader/src/main/resources 
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ bookreader --- 
[INFO] Compiling 3 source files to /home/steven/maven-conversion/bookreader/target/classes 
[INFO] 
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ bookreader --- 
[INFO] Using 'UTF-8' encoding to copy filtered resources. 
[INFO] Copying 4 resources 
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ bookreader --- 
[INFO] Compiling 5 source files to /home/steven/maven-conversion/bookreader/target/test-classes 
[INFO] 
[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ bookreader --- 
[INFO] Surefire report directory: /home/steven/maven-conversion/bookreader/target/surefire-reports 

------------------------------------------------------- 
T E S T S 
------------------------------------------------------- 
Running net.stevenpeterson.base.LoadStringUtilityTest 
Tests run: 3, Failures: 3, Errors: 0, Skipped: 0, Time elapsed: 0.041 sec <<< FAILURE! 
Running net.stevenpeterson.base.SplitStringUtilityTest 
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec 
Running net.stevenpeterson.booksplitter.BookSplitterTest 
Tests run: 4, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 0.007 sec <<< FAILURE! 

Results : 

Failed tests: 
    testSingleLine(net.stevenpeterson.base.LoadStringUtilityTest): Unable to find load file: singleLine 
    testSeveralLines(net.stevenpeterson.base.LoadStringUtilityTest): Unable to find load file: severalLines 
    loadSherlockHolmes(net.stevenpeterson.base.LoadStringUtilityTest): Exception thrown while loading: cano.txt 
    ThirdLineOfAlphabetTest(net.stevenpeterson.booksplitter.BookSplitterTest): IOException thrown while loading test file. 
    OutOfRangeLineOfAlphabetTest(net.stevenpeterson.booksplitter.BookSplitterTest): IOException thrown while loading test file. 
    SectionSizeTwoAlphabetTest(net.stevenpeterson.booksplitter.BookSplitterTest): IOException thrown while loading test file. 
    LastLineOfAlphabetTest(net.stevenpeterson.booksplitter.BookSplitterTest): IOException thrown while loading test file. 

>  Tests run: 12, Failures: 7, Errors: 0, Skipped: 0 
>  
>  [INFO] ------------------------------------------------------------------------ 
>  [INFO] BUILD FAILURE 
>  [INFO] ------------------------------------------------------------------------ 
>  [INFO] Total time: 1.634s 
>  [INFO] Finished at: Tue Nov 29 19:41:59 MST 2011 
>  [INFO] Final Memory: 15M/105M 
>  [INFO] ------------------------------------------------------------------------ 
>  [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.7.2:test 
> (default-test) on project bookreader: There are test failures. 
>  [ERROR] 
>  [ERROR] Please refer to /home/steven/maven-conversion/bookreader/target/surefire-reports for 
> the individual test results. 
>  [ERROR] -> [Help 1] 
>  [ERROR] 
>  [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. 
>  [ERROR] Re-run Maven using the -X switch to enable full debug logging. 
>  [ERROR] 
>  [ERROR] For more information about the errors and possible solutions, please read the following articles: 
>  [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException 


Contents of: /home/steven/maven-conversion/bookreader/target/test-classes 
AlphabetTest cano.txt net/ severalLines singleLine 

It looks as if Maven is placing the resources in the correct location, I think I'm confused about the relative path that is being used when I execute my tests. 
+0

時々、私はMavenを使用して、いくつかのオープンソースのJavaベースのプロジェクトと同じ問題に直面し、中にあるテストファイルとのユニットテストを含めます異なるパッケージ/フォルダ。だから、私が問題を解決するために使用する迅速かつ汚いアプローチは、各テストファイルのパッケージ/フォルダの完全なパスを含めることです。 –

答えて

5

通常、私のテスト関連のプレーンテキストファイルは、リソースファイルをテストするためのデフォルトのディレクトリである(src/test/javaユニットテストとともに)指定されたプロジェクトのsrc/test/resourcesディレクトリに置かれます。 ..あなたはおそらくあなたのpom.xmlファイルを見てこれをやっているようです。ちなみに、それはデフォルトの場所なので、おそらくそれを呼び出す必要はありません。あなたはクラスローダを使用してそれらのファイルをロードすることができますユニットテストから

InputStream is = SomeClass.class.getResourceAsStream("cano.txt";); 

あなたの問題は、あなたのLoadStringUtilityクラスであってもよいように思えます。あなたのLoadStringUtilityがどのようなものかわからなければ、間違っているかもしれない何かについての指示はできません。

ストリームをストリングにロードしているようです。

String output = IOUtils.toString(is); 

LoadStringUtilityにつながる可能性があり、次のようになります:

public class LoadStringUtility { 

    public static String loadStringFromFile(String file) throws IOException { 
     InputStream inputStream = LoadStringUtility.class.getClassLoader().getResourceAsStream(file); 
     return IOUtils.toString(inputStream); 
    } 
} 
+0

素敵な答えです。リソースに先行する "/"が必要なのか、それともルートが暗黙であるのか? – Gray

+0

getResourceAsStream()はクラスパスからリソースを返します。ルートは暗黙指定されており、先頭にスラッシュを追加しないでください。 –

+0

あなたはそのコメントで私に何を見せているのか分かりませんが、明確にすることはできますか? –

0

をところであなたはいけない一般的に私は、文字列に入力ストリームの内容を引くためにはApache CommonsのIO IOUtilsヘルパークラスを使用しますデフォルトではそのままであるので、src/test/resourcesbuildに指定する必要があります。

Plsが<your_app_base_path>/target/test-classesであることを確認します。

は、私はあなたがロードしているか知らないが、あなたは私が簡単にアクセスできるだけでなく、いくつかの修正とここに更新していますLoading a property file by reading line by line from another file

で私の返事を参照することができます。

​​

コードはそれを呼び出すために。いろいろな方法があります。

  • クラスローダのベースからプロパティをロードする場合。例えば、私がmain関数を使って私のアプリケーションをeclipseから実行している場合、私のベースは<some_path>/classesになります。ファイルlabel.propertiesがそこに住んでいます。また、Tomcatから実行しており、label.properties<your_web_app>/classesにある場合テストケースを実行している場合は、<app_base_path>/target/test-classes、それ以外の場合は<app_base_path>/target/classesになります。コードの下に使用します。

    createInputStream("/" + line, PathType.RESOURCE); // Load from base path of class loader

  • あなたはクラスローダのパッケージフォルダからプロパティをロードする場合。例えば、私がmain関数を使って私のアプリケーションをeclipseから実行している場合、私のベースは<some_path>/classesになります。ファイルlabel.properties<some_path>/classes/testing/projectに存在します。あなたは<your_web_app>/classes/testing/projectでTomcatとlabel.properties liesから実行している場合にも、コードの下に使用します。

    createInputStream(line, PathType.RESOURCE); // Load from base path of class loader + the package path

  • あなたのハードドライブ上の任意の絶対パスからロードプロパティをしたい場合。コードの下に使用します。

    createInputStream("C:\\apps\\apache\\tomcat7\\webapps\\examples\\WEB-INF\\classes\\" + line, PathType.ABSOLUTE);

注:Plsはあなたの必要性ごとに例外を処理します。また、あなたの必要に応じて、または私はいくつかのインポートを逃した場合はそれを変更します。 Mavenは、最初に述べたように最後の2つのケースで同じように動作します。ちょうど常識を使用してください。

+0

良いチップありがとう。 – Shaftoe2702

0

このケースでは、私が探しているのは、特定のリソースへのパスです。与えられた答えの情報は、私が次のものを一緒に投げ込むのを助けました:
パッケージnet.stevenpeterson.bookreaderlib;

私がテストクラスを変更し、ことに続き
import java.net.URL; 

public class ResourceLookup { 

    private ResourceLookup(){ 
    } 

    public static String getPathForResource(String name){ 
     ResourceLookup lookupInstance = new ResourceLookup(); 
     URL aURL = lookupInstance.getClass().getClassLoader().getResource(name); 
     return aURL.getPath(); 
    } 
} 

package net.stevenpeterson.bookreaderlib; 

import static org.junit.Assert.*;  

import net.stevenpeterson.bookreaderlib.LoadStringUtility; 
import net.stevenpeterson.bookreaderlib.ResourceLookup; 

import org.junit.Before; 
import org.junit.Test; 

public class LoadStringUtilityTest { 


    private String singleLine; 
    private String severalLines; 
    private String cano; 



    @Test 
    public void testGetURLMethod(){ 
     String resourcePath = ResourceLookup.getPathForResource("singleLine"); 
     assertNotNull("URL to singleLine should not be null", resourcePath); 
    } 

    @Test 
    public void testSingleLine() { 
     assertEquals("Loading File", "This is a test." , loadFile(singleLine)); 
    } 

    @Test 
    public void testSeveralLines() { 
     assertFalse("Compare a string appended with extra lines, should not compare true. ", "This is a test.".equals(loadFile(severalLines))); 
    } 

    @Test 
    public void loadSherlockHolmes() { 
     String fileToLoad = this.cano; 
     try{ 
     StringBuilder holmesCanon = LoadStringUtility.LoadString(fileToLoad); 
     System.out.println("Finished Loading file: chars read=" + holmesCanon.length()); 
     assertTrue("loading size of file:", true); 
     }catch(Exception e){ 
     fail("Exception thrown while loading: " + fileToLoad); 
     } 

    } 


    private String loadFile(String fileName) { 
     StringBuilder loadedFromFile = new StringBuilder(); 
     try { 
      loadedFromFile = LoadStringUtility.LoadString(fileName); 
     } catch (Exception e) { 
      fail("Unable to find load file: " + fileName); 
      e.printStackTrace(); 
     } 
     return loadedFromFile.toString(); 
    } 


    @Before 
    public void loadAllResources(){ 
     **this.singleLine = ResourceLookup.getPathForResource("singleLine"); 
     this.severalLines = ResourceLookup.getPathForResource("severalLines"); 
     this.cano = ResourceLookup.getPathForResource("cano.txt");** 
    } 
} 
+0

これをテストしたシステムはどれですか、WindowsまたはUnixのフレーバーですか? – havexz

+0

Unixしかし、私はパスを構築しないので、コードは移植性があると信じています。 – Shaftoe2702

+0

私はそう思っていました。窓で試してみました。 "/C:\somepath"..(iは/ /スラッシュかどうか忘れてしまいました)のようなパスがあります。私はそれに深く見える機会を得なかった... btは観察を共有するように... – havexz

関連する問題