我最近开始使用 NUnit 框架为我的代码编写单元测试。
我熟悉 NUnit 的基本概念并编写简单的测试。
实际上我不知道如何测试与文件一起使用的代码:例如,我想为下面的类编写测试:
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;
}
}
}
这段代码需要物理文件来检查它是否工作正常,但是单元测试是否依赖于物理文件?
如何为这样的代码编写单元测试?