Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing a CSV Parser and Column Mapping Tool

I am really starting to enjoy unit testing and have the following question to the gurus of unit testing.

Let's for example say I have the following class

public class FileMapper
{
   public Dictionary<string, string> ReadFile(string filename, string delimeter){}
}

How do you guys generally go about unit testing a Parser or ReadFile method in my case?

like image 805
Pieter Germishuys Avatar asked May 10 '26 02:05

Pieter Germishuys


1 Answers

Given the method signature you provided, you can 'simply' unit test the ReadFile method by invoking it with a lot of different input and verify that the return value is correct.

However, this can lead to Obscure Tests because very important test input is hidden away in files instead of being visible when you review each test.

This is where TDD shows its force because it should prompt us to consider a better API.

You could, for example, change the method to this:

public Dictionary<string, string> ReadFile(TextReader reader, string delimeter)

It's still pretty easy to get a TextReader from a file, but now you can alternatively use a StringReader to supply unit test input.

This change will not only make it easier to unit test the ReadFile method, but also make the method more generally usable because it no longer has a tight coupling to the file system.

like image 56
Mark Seemann Avatar answered May 12 '26 09:05

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!