[英]NUnit: Write unit test for code needs work with physical file
我最近開始使用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;
}
}
}
此代碼需要對物理文件進行檢查才能正常工作,但是單元測試對物理文件具有依賴性嗎?
如何為此類代碼編寫單元測試?
單元測試不應與外部資源(例如文件系統或數據庫等)有任何依賴關系。在這種情況下,您必須使用Moq或Rhino Mock等模擬框架。 如果要測試代碼及其外部依賴項,則應編寫Integration Test
。
因此,在您的情況下,如果您不想使用任何模擬框架,則可以為依賴關系創建自己的偽類,並通過依賴關系注入模式傳遞它們
我喜歡創建這個:
public abstract class FileSystem
{
public abstract bool FileExists(string fullPath);
public abstract Stream OpenFile(string fullPath, FileMode mode, FileAccess access);
}
然后,您可以以明顯的方式為生產代碼實現它,並為測試代碼輕松模擬它。
[Test]
public void StreamReadingEventAddsStreamToEventArgsWhenFileExists()
{
var e new StreamReadingEventArgs { e.AlternateStreamName= "Random string in path format", e.FileMode = AnyFileMode(), e.FileAccess = AnyFileAccess() };
var expectedStream = new MemoryStream();
_fileSystemMock.Setup(f=>f.OpenFile(e.AlternateStreamName, e.FileMode, e.FileAccess)).Returns(expectedStream);
SomehowFireTheEvent(e);
Assert.That(e.AlternateStream, Is.SameAs(expectedStream));
}
作為附帶說明,此代碼還有其他可測試性問題,這些問題會使您感到沮喪。 我建議嘗試為此編寫一些測試,然后將生產代碼和測試發布到codereview.stackexchange.com上以獲取一些反饋。
無論您擁有的依賴項或正在使用的外部資源如何,都為它們中的每一個創建模擬,然后使用模擬框架(如MOQ)運行測試。 這是一個例子。 更好地創建接口並使用接口實現模擬
var mockEmailRequest = new Mock<IEMailRequest>
mockEmailResponse.setup(x+>x.EmailResponse).Returns(.....);
mockEmailRequest.Verify(r=>r.EmailReceived(It.Is<EmailResponse>(r=>r.Subject == "Something"),It.Is<int>(i=>i > 17)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.