I’ve recently started writing unit tests for my codes using NUnit framework.
I am familiar with basic concepts of NUnit and writing simple tests.
Actually I don’t know how to test codes that work with files :
for example I want to write test for below class :
public class ShapeLoader
{
private static void StreamLoading(object sender, StreamLoadingEventArgs e)
{
try
{
string fileName = Path.GetFileName(e.AlternateStreamName);
string directory = Path.GetDirectoryName(e.AlternateStreamName);
e.AlternateStream = File.Exists(directory + @"\\" + fileName) ? new FileStream(directory + @"\\" + fileName, e.FileMode, e.FileAccess) : null;
}
catch
{ }
}
public static ShapeFileFeatureLayer Load(string filePath, ShapeFileReadWriteMode shapeFileReadWriteMode, bool buildIndex = true)
{
if (!File.Exists(filePath)) { throw new FileNotFoundException(); }
try
{
switch (shapeFileReadWriteMode)
{
case ShapeFileReadWriteMode.ReadOnly:
// if (buildIndex && !HasIdColumn(filePath)) BuildRecordIdColumn(filePath, BuildRecordIdMode.Rebuild);
ShapeFileFeatureLayer.BuildIndexFile(filePath, BuildIndexMode.DoNotRebuild);
var shapeFileLayer = new ShapeFileFeatureLayer(filePath, shapeFileReadWriteMode) { RequireIndex = true };
((ShapeFileFeatureSource)shapeFileLayer.FeatureSource).StreamLoading += StreamLoading;
return shapeFileLayer;
case ShapeFileReadWriteMode.ReadWrite:
return new ShapeFileFeatureLayer(filePath, shapeFileReadWriteMode);
default:
return null;
}
}
catch (Exception ex)
{
if (ex.Message.Contains("Could not find file")) throw new FileNotFoundException();
throw;
}
}
}
This code needs to physical file to check if it works fine or not , but Is this right that unit test has dependency with physical files ?
How do I write unit tests for codes like this ?
Unit tests should not have any dependencies to external resources such as file system or database, etc.
in these case you must use mocking frameworks such as Moq or Rhino Mock.
If you want to test your code and it’s external dependencies you should write
Integration Test.So In your case, if you don’t want to use any mocking framework, you can create your own fake classes for dependencies and pass them by Dependency Injection Pattern