我編寫了一個用於檢查文件路徑的測試用例。在那個測試用例中,我使用Expected異常,然後我想知道如果該方法不會拋出文件未找到異常會發生什麼。處理預期的單元測試異常C#
例如,我在另一個系統中運行測試用例,如果系統中存在給定的文件路徑,測試將失敗。但它不應該是,測試用例應該總是通過。
如何處理這種情況,因爲單元測試不依賴於任何示例應該不依賴於機器?
測試的情況下......
string sourceFilePath = @"C:\RipWatcher\Bitmap.USF_C.usf";
string targetDirectory = @"C:\UploadedRipFile\";
[Test]
[ExpectedException(typeof(FileNotFoundException))]
public void InvalidSourceFilePathThrowsFileNotFoundException()
{
logWriter= new Mock<LogWriter>().Object;
ripfileUploader = new RipFileUploader(logWriter);
ripfileUploader.Upload(@"D:\RipWatcher\Bitmap.USF_C.usf",
targetDirectory);
}
方法..
public void Upload(string sourceFilePath, string targetFilePath)
{
if (!File.Exists(sourceFilePath))
{
throw new FileNotFoundException(string.Format("Cannot find the file: {0}", sourceFilePath));
}
if (!Directory.Exists(targetFilePath))
{
throw new DirectoryNotFoundException(string.Format("Cannot find the Directory: {0}", targetFilePath));
}
try
{
fileCopyEx.CopyEx(sourceFilePath,targetFilePath);
}
catch (Exception ex)
{
throw new Exception(string.Format("Failed to move file {0}", sourceFilePath), ex);
}
}
「不應該依賴於機器」 - 是的,它不應該。但它*確實* - 因爲你是這樣寫的。它取決於本地文件系統上目錄的存在。 – BartoszKP
這裏的測試是一個集成測試,而不是一個單元測試,因爲它測試文件系統以及使用它的代碼。如果您使代碼可測試並使用單元測試,問題就會消失 - 抽象文件和目錄類並使用可以模擬的接口。 –