Reputation: 187
I want to make sure that my C# program reads a file as expected. How should I test this? I am assuming I just call my function (which accesses the file system) and see the output when a file exist and when it doesn't. Should I instead abstract the file system out?
Should I even bother testing this (since I am basically testing if StreamReader.ReadLine
works)?
My function looks like this (filePath, filePath2, a and b are arguments to the function)
try
{
TextReader tr = new StreamReader(filePath);
a = tr.ReadLine();
b = tr.ReadLine();
tr.Close();
}
catch (Exception ex)
{
error = GetError(ex);
}
if (error != "") {
File.WriteAllText(filePath2+"Error.txt", error);
}
Upvotes: 0
Views: 687
Reputation: 100527
Two most common approaches: facade for all file IO operations (so you can mock it) or refactor code that you only need to test pieces that take easy to mock objects like Stream
.
Sample second approach: refactor your code into piece that deals with getting stream and another one that actually read the data:
public class MyClass
{
.............
string a;
string b;
public ReadTheData(Stream stream)
{
try
{
TextReader tr = new StreamReader(stream);
a = tr.ReadLine();
b = tr.ReadLine();
tr.Close();
}
catch (Exception ex)
{
// awful practice... Don't eat all exceptions
error = GetError(ex);
}
if (error != "") {
// whatever log infrastructure you have, need to be mock-able for tests
Logger.Log(error);
}
}
}
Now you can unit test ReadTheData
method without any access to file system by passing filled out MemoryStream
or even mocked out stream.
Upvotes: 1