java在maven项目中从主包访问测试资源
作为练习的一部分,我正在开发代码,该代码将读取一个文件并检查它是否有浮动。我已经编写了代码,但我不确定是否正确访问了文件,或者是否有更好的方法
应用程序:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Question1 {
/* Write a method public ArrayList<Double> readValues(String filename) throws ... that reads a file
* containing floating-point numbers. Throw appropriate exceptions if the file could not be opened
* or if some of the inputs are not floating-point numbers.
*/
private static final String RESOURCE_BASE_PATH = "src/test/resources/";
//under src/main/ java : java_impatient.chapter4.Question1
public static List<Double> readValues(String filename) throws IOException {
ArrayList<Double> values = new ArrayList<>();
try (BufferedReader fileReader = new BufferedReader(new FileReader(filename))) {
//TODO : Complete this with TDD ?
}
return values;
}
}
测试:
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.*;
import java.util.List;
public class Question1Test {
//Some other test code here.
//under src/test : testjava_impatient.chapter4.Question1Test
@Test
public void returnsEmptyListForEmptyFile() throws Exception {
//Is this the best way to get the full path of a file?
List<Double> values = Question1.readValues( getFilePath("src/test/resources/chapter4/question1_empty.txt") );
Assert.assertTrue(values.isEmpty(), "List is not empty as expected!");
}
private static String getFilePath(String relativePath){
File file = new File(RESOURCE_BASE_PATH + relativePath);
String fullPath = file.getAbsolutePath();
return fullPath;
}
}
# 1 楼答案
Maven默认情况下将“.java”文件打包为“src/*/java”中的“.class”和“src/*/resources”中的“*”文件,您不会使用“src/*/*”,因为编译后它不存在
只需使用java和resources文件夹中的文件夹结构
另外,不要忘记,您想要访问的文件可能在运行的jar中,或者在ide生成的构建结构中
如果您没有更改资源的打包方式,要访问资源,您可以使用:
您可以使用相对路径或绝对路径(在resources文件夹中)
例如:
使用InputStreamReader代替FileReader