saveCSV 的 JUnit 测试

JUnit testing for saveCSV

我是 JUnit 测试的新手,我想编写一个保存 CSV 文件的测试。由于该方法没有 return 值,我想测试数据是否成功保存在 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 class.

编辑: 此外,savePlayer 可以通过使用 try with resources.

变得更简单