2

我有我创建的这个方法:

 public static bool DeleteFile(FileInfo fileInfo)
    {
        try
        {
            fileInfo.Delete();
            return true;
        }
        catch (Exception exception)
        {
            LogManager.LogError(exception);
            return false;
        }
    }

现在我写了以下单元测试:

[TestMethod]
    public void DeleteFileSuccessFul()
    {
        string fileName = "c:\\Temp\\UnitTest3.txt";
        FileInfo fileInfo = new FileInfo(fileName);

        File.Create(Path.Combine(fileName));

        bool success = FileActions.DeleteFile(fileInfo);

        Assert.IsTrue(success);
    }

此测试失败,因为该文件正在由不同的进程使用。测试在 het bool success = FileActions.DeleteFile(fileInfo); 上失败 因为该文件正在由不同的进程使用。

如何更改我的测试以使其正常工作?

4

1 回答 1

7

您必须对该方法返回的对象调用Dispose方法以释放该文件的句柄:FileStreamFile.Create

[TestMethod]
public void DeleteFileSuccessFul()
{
    string fileName = "c:\\Temp\\UnitTest3.txt";
    FileInfo fileInfo = new FileInfo(fileName);

    using (File.Create(Path.Combine(fileName)))
    {
    }

    bool success = FileActions.DeleteFile(fileInfo);

    Assert.IsTrue(success);
}

UPDATE: block 提供了一种方便的语法,即使发生异常using,也可以确保在离开块范围后调用对象的Dispose方法。IDisposable上面代码的等价物可以用块重写try-finally

[TestMethod]
public void DeleteFileSuccessFul()
{
    string fileName = "c:\\Temp\\UnitTest3.txt";
    FileInfo fileInfo = new FileInfo(fileName);

    FileStream fileStream = null;
    try
    {
        fileStream = File.Create(Path.Combine(fileName));
    }
    finally
    {
        if (fileStream != null)
            fileStream.Dispose();
    }

    bool success = FileActions.DeleteFile(fileInfo);

    Assert.IsTrue(success);
}
于 2013-06-28T07:14:39.410 回答