处理单元测试 C# 中的预期异常

本文关键字:异常 单元测试 处理 | 更新日期: 2023-09-27 18:32:21

我写了一个测试用例来检查文件路径。在该测试用例中,我使用了预期异常,然后我想知道如果该方法不会抛出文件未找到异常会发生什么。

例如,我在另一个系统中运行测试用例,如果系统中存在给定的文件路径,则测试将失败。但不应该是,测试用例应该始终通过。

如何处理这种情况,因为单元测试不依赖于任何示例不应依赖于机器?

测试用例...

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);        
    }          
}

处理单元测试 C# 中的预期异常

如果您希望这样的方法可测试并且独立于它运行的机器 - 则不应直接使用FileDirectory类。

相反,从您需要的所有类中提取具有方法的接口,编写此接口的实现,该接口使用FileDirectory类的方法。

public interface IFileManager 
{
    bool IsFileExists(string fileName);
    ....
}
public class FileManager : IFileManager
{
     public bool IsFileExists(string fileName)
     {
        return File.Exists(fileName);
     }
}
public void Upload(string sourceFilePath, string targetFilePath, IFileManager fileManager)
{
    if (!fileManager.IsFileExists(sourceFilePath))
    {
        ....
    }
}

在工作环境中,您将使用此实现,在测试环境中,您必须创建实现此接口的模拟对象。因此,您可以根据需要的任何方式设置此模拟。

[Test]
[ExpectedException(typeof(FileNotFoundException))]
public void InvalidSourceFilePathThrowsFileNotFoundException()
{
    fileManager = new Mock<IFileManager>();        
    fileManager.Setup(f => f.IsFileExists("someFileName")).Returns(false);
    ripfileUploader = new RipFileUploader(logWriter);
    ripfileUploader.Upload(@"D:'RipWatcher'Bitmap.USF_C.usf", 
                           targetDirectory, 
                           fileManager.Object);            
}

如果你想要确定性的结果,你必须确保该文件不存在于任何机器上。

string sourceFilePath = @"C:'RipWatcher'Bitmap.USF_C.usf";
string targetDirectory = @"C:'UploadedRipFile'";
[Test]
[ExpectedException(typeof(FileNotFoundException))]
public void InvalidSourceFilePathThrowsFileNotFoundException()
{
    File.Delete(@"D:'RipWatcher'Bitmap.USF_C.usf");
    logWriter= new Mock<LogWriter>().Object;
    ripfileUploader = new RipFileUploader(logWriter);
    ripfileUploader.Upload(@"D:'RipWatcher'Bitmap.USF_C.usf",       
    targetDirectory);            
}

否则,您的测试不是确定性的,您可以将其丢弃。另一种可能性是将访问文件系统的代码放在一个单独的类中,并为始终引发异常的测试提供 RipFileUploader 的模拟实现。