Maven没有看到我在单元测试中使用的一些文本文件

Sha*_*702 2 java junit pom.xml maven

我正在用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我的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>
Run Code Online (Sandbox Code Playgroud)

当我运行单元测试时:


steven@steven-desktop:~/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.
Run Code Online (Sandbox Code Playgroud)

Joh*_*sen 5

我通常将我的测试相关纯文本文件放在给定项目下的src/test/resources目录下(以及src/test/java单元测试),这是测试资源文件的默认目录...它看起来像你可能是通过查看你的pom.xml文件来做到这一点的.顺便说一下,由于它是默认位置,您可能不需要将其调出.

从单元测试中,您可以使用类加载器加载这些文件:

InputStream is = SomeClass.class.getResourceAsStream("cano.txt";);
Run Code Online (Sandbox Code Playgroud)

看起来你的问题可能出在你的LoadStringUtility类中.在不知道你的LoadStringUtility看起来是什么样的情况下,我无法就可能出现的问题给出任何指示.

看起来您正在将流加载到String中.通常我会使用Apache Commons IO IOUtils帮助程序类将输入流内容拉入String:

String output = IOUtils.toString(is);
Run Code Online (Sandbox Code Playgroud)

这可能会导致LoadStringUtility看起来像这样:

public class LoadStringUtility {

    public static String loadStringFromFile(String file) throws IOException {
        InputStream inputStream = LoadStringUtility.class.getClassLoader().getResourceAsStream(file);
        return IOUtils.toString(inputStream);
    }
}
Run Code Online (Sandbox Code Playgroud)