我正在用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>
当我运行单元测试时:
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.
答案 0 :(得分:5)
我通常将测试相关的纯文本文件放在给定项目下的src / test / resources目录下(以及src / test / java单元测试),这是测试资源文件的默认目录...看起来你可能正在查看你的pom.xml文件。顺便说一句,由于它是默认位置,您可能不需要将其调出。
从单元测试中,您可以使用类加载器加载这些文件:
InputStream is = SomeClass.class.getResourceAsStream("cano.txt";);
好像你的问题可能出在你的LoadStringUtility类中。在不知道你的LoadStringUtility看起来是什么样的情况下,我无法就可能出现的问题给你任何指示。
看起来您正在将流加载到String中。通常我会使用Apache Commons IO IOUtils帮助程序类将输入流内容拉入字符串:
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);
}
}
答案 1 :(得分:0)
顺便说一下,您不需要将src/test/resources
指定为build
,因为默认情况下就是这样。
请确认<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;
}
调用它的代码。有各种各样的方式。
如果要从类加载器的基础加载属性。例如,如果我使用eclipse中的main
函数运行我的应用程序,我的基础将是<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
如果要从类加载器的包文件夹加载属性。例如,如果我使用eclipse中的main
函数运行我的应用程序,我的基础将是<some_path>/classes
。文件label.properties
位于<some_path>/classes/testing/project
。此外,如果您从Tomcat运行并且label.properties
位于<your_web_app>/classes/testing/project
,请使用以下代码:
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);
注意:请根据您的需要处理异常。也可以根据需要修改它,或者如果我错过了一些进口。如前所述,Maven在前两种情况下的行为相同,只是使用常识。
答案 2 :(得分:0)
对于这种情况,无论好坏,我正在寻找的是特定资源的路径。在给出的答案中的信息帮助我把以下内容放在一起:
package 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");**
}
}