[英]How to read file from src/main/resources relative in a JUnit test?
[英]How to read csv file from resources dir in JUnit Test using FileUtils
在標准Maven項目的資源目錄中包含一個csv文件,如下所示:
src/main/resources/fruits.csv
src/test/resources/fruits.csv
fruits.csv
Type, Quantity
apple, 50
banana, 60
orange, 70
使用以下庫
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
水果(標准POJO)
public class Fruit {
private String type
private int quantity;
public Fruit(String type, int quantity) {
this.type = type;
this.quantity = quantity;
}
// Getters & Setters
}
CsvFileReader
public class CsvFileReader {
private static final String [] FILE_HEADER = {""};
private static final String TYPE = "Type";
private static final String QUANTITY + "Quantity";
public static List<Candidate> readCsvFile(File fileName) {
FileReader fileReader = null;
CSVParser csvFileParser = null;
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
List<Candidate> fruits = null;
try {
fruits = new ArrayList<>();
String file = FileUtils.readFileToString(fileName);
fileReader = new FileReader(file);
csvFileParser = new CSVParser(fileReader, csvFormat);
List<CSVRecord> records = csvFileParser.getRecords();
for (int i = 1; i < records.size(); i++) {
CSVRecord record = records.get(i);
Fruit fruit = new Fruit(record.get(TYPE), Integer.parseInt(QUANTITY));
fruits.add(fruit);
}
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try {
fileReader.close();
csvFileParser.close();
} catch(IOException e) {
e.printStackTrace();
}
}
return fruits;
}
}
CsvFileReaderTest(JUnit 4測試用例):
public class CsvFileReaderTest {
File csvFile = null;
@Before
public void setUp() throws Exception {
String userDir = System.getProperty("user.dir");
String filePath = userDir + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
csvFile = FileUtils.getFile(filePath + "fruits.csv");
}
}
當我在Eclipse中運行JUnit測試用例時:
java.io.FileNotFoundException: Type, Quantity
apple, 50
banana, 60
orange, 70
(File name too long)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
似乎正在讀取文件,但問題是FileName太長?
我究竟做錯了什么?
FileReader
構造函數需要傳遞文件內容的文件路徑。 您可以直接使用采用CSV String
CSVParser
構造函數。
csvFileParser = new CSVParser(file /*This is already file content*/, csvFormat);
**編輯**
更好的辦法是獲取資源的閱讀器,並將其傳遞給CSVParser構造函數:
reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("fruits.csv")));
csvFileParser = new CSVParser(reader, csvFormat);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.