编写unittest来创建文件然后删除该文件

时间:2013-06-28 07:09:28

标签: c# unit-testing visual-studio-2012

我创建了这个方法:

 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);因为该文件正由另一个进程使用。

如何更改测试以使其有效?

1 个答案:

答案 0 :(得分:6)

您必须在Dispose方法返回的FileStream对象上调用File.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: 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);
}