gpt4 book ai didi

java - saveCSV 的 JUnit 测试

转载 作者:太空宇宙 更新时间:2023-11-04 14:11:33 25 4
gpt4 key购买 nike

我是 JUnit 测试的新手,我想编写一个用于保存 CSV 文件的测试。由于该方法没有返回值,我想测试数据是否成功保存到csv文件中。有谁知道如何测试它?我的类(class)是:

private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
private String file_position;

public SaveCSV(String file_position){
this.file_position = file_position;
File file = new File(file_position);
file.mkdir();
}

public void savePlayer(HashMap<Integer, Player> Player_HASH) {
String fileName = file_position+"player.csv";
String FILE_HEADER = "id,name,color,order" + NEW_LINE_SEPARATOR;

FileWriter fileWriter = null;

try {
fileWriter = new FileWriter(fileName);
fileWriter.append(FILE_HEADER.toString());

for(Player player : Player_HASH.values()){
fileWriter.append(String.valueOf(player.getID()));
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(player.getName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(player.getColor().toString());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(String.valueOf(player.getOrder()));
fileWriter.append(NEW_LINE_SEPARATOR);
}

} catch (Exception e) {
System.out.println("Error in CsvFIleWriter!");
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
System.out.println("Error while flushing/closing fileWriter!");
e.printStackTrace();
}
}
}

最佳答案

测试这一点的直接方法是运行代码并读取输出。我首先建议更改 SaveCSV 以接受 File (它比 String 类型更安全),并且不要在构造函数中创建目录(因为在构造函数中执行工作是有问题的):

public SaveCsv {
private final File file;

public SaveCsv(File file){
this.file = file
}

public void savePlayer(Map<Integer, Player> playerHash) {
if (!file.exists()) {
file.mkdir();
}
...
}
}

然后你可以这样测试:

@RunWith(JUnit4.class)
public class SaveCsvTest {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();

@Test
public void savePlayerShouldWriteCsv() {
File file = testFolder.newFolder("folder");
SaveCsv saveCsv = new SaveCsv(file);
InputStream stream = new FileInputStream(file);
Reader reader = new InputStreamReader(
stream, StandardCharsets.UTF_8);
// compare contents of data
}

如果您想避免在测试中写入实际文件,我建议让 SaveCsv 的构造函数使用 Guava 的 CharSink类。

编辑:此外,使用 try with resources 可以使 savePlayer 变得更简单。 .

关于java - saveCSV 的 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28265014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com