2011-11-30 1 views
2

저는 Maven에 젖은 채로 젖 혔지 만 가파른 학습 곡선입니다. 단위 테스트 내에서 일반 텍스트 파일을로드하려고합니다. 테스트가 통과되었으므로 이제 프로젝트를 maven 프로젝트로 변환했습니다. 테스트 파일이있는 위치에서 테스트가 해결되지 않는 것 같습니다.Maven에서 내 단위 테스트에서 사용하는 일부 텍스트 파일을 볼 수 없습니다.


:


<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> 

내가 단위 테스트를 실행하면 :

// 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 파일입니다
[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

:

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(); } } 

그 후, 나는 테스트 클래스를 수정 다른 패키지/폴더. 그래서, 내가이 문제를 해결하기 위해 사용하는 빠르고 더러운 접근법은 각 테스트 파일의 패키지/폴더의 전체 경로를 포함하는 것입니다. –

답변

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

을 BTW 당신이 그나마 일반적으로 내가 문자열로 입력 스트림의 내용을 끌어 아파치 커먼즈 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

에 내 대답을 참조 할 수 있습니다 :

package testing.project; 

import java.io.*; 

enum PathType {RESOURCE, ABSOLUTE} 

private static InputStream createInputStream(String line, PathType pathType) { 
    InputStream in = null; 
    if (pathType == PathType.RESOURCE) 
     in = PropertyTest.class.getResourceAsStream(line); 
    else { 
     try { 
      in = new FileInputStream(line); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 
    return in; 
} 

코드를 호출 할 수 있습니다. 다양한 방법이 있습니다.

  • 클래스 로더의 기본 속성을로드하려는 경우. 예를 들어, main 함수를 사용하여 응용 프로그램을 실행할 경우 Eclipse는 <some_path>/classes이됩니다. 따라서 파일 label.properties이 거기에 거주하고 있습니다. 또한 Tomcat에서 실행중인 경우 label.properties<your_web_app>/classes에 있습니다. 테스트 케이스를 실행하는 경우에는 maven에서 <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에서 톰캣과 label.properties 거짓말에서 실행하고 또한 경우, 코드 아래 사용

    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은 처음 언급 한 것처럼 마지막 두 경우에 똑같이 동작 할 것이고, 단지 상식을 사용합니다.

+0

팁 감사합니다. – Shaftoe2702

0

이 경우에는 더 좋든 나쁘 든간에 특정 리소스에 대한 경로 만 찾고 있습니다. 주어진 답에 대한 정보는 다음을 함께 던지는데 도움이되었습니다 :
package net.stevenpeterson.bookreaderlib; 나는에있는 테스트 파일과 단위 테스트를 메이븐을 사용 등 몇 가지 오픈 소스 자바 기반의 프로젝트와 같은 문제에 직면 때로는

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

이 시스템을 테스트 해본 시스템은 어느 것입니까? – havexz

+0

유닉스이지만 경로를 만들지 않아 코드가 이식 가능하다고 생각합니다. – Shaftoe2702

+0

나는 그렇게 생각했다. 나는 창문에서 그것을 시험해 보았다. "/C:\somepath"..((i는/또는 \ slash인지 잊어 버렸다)와 같은 경로가있다. 나는 그것을 깊이 들여다 볼 기회를 얻지 못했다. 관찰을 공유하고 싶다. – havexz

관련 문제