New project from FarawayTech: Zima Weather — Weather and calendar dashboard for busy professionals.
CSV Parsing Unit Testing
Here we are going to look at how to unit test CSV parsing. The test will go as following:
- We create CSV record objects in C#
- We write CSV records to a file
- 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)) {
csv.WriteHeader<CsvRecord>();
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:
Assert.IsTrue(records.SequenceEqual(newRecords));