我编写了一个用于检查文件路径的测试用例。在那个测试用例中,我使用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
这里的测试是一个集成测试,而不是一个单元测试,因为它测试文件系统以及使用它的代码。如果您使代码可测试并使用单元测试,问题就会消失 - 抽象文件和目录类并使用可以模拟的接口。 –