CSV Parsing Unit Testing

Here we are going to look at how to unit test CSV parsing. The test will go as following:

  1. We create CSV record objects in C#
  2. We write CSV records to a file
  3. We read the file and compare CSV records are the same

Let's create some simple records first:

var records = ImmutableList.Create(new CsvRecord() { Name="X", FieldFloat=1.0, FieldInt=1 })

Next, write the records to a file:

await using var writer = new StreamWriter("file.csv");
await using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) {
    await csv.NextRecordAsync();
    await csv.WriteRecordsAsync(records);

Then you would typically call a function from your service that reads the CSV file, such as one we defined in CSV Parsing Intro:

var newRecords = ParseCsvFile("file.csv");

Finally, we compare the resulting collections to make sure they are the same: