Bart Schelkens
Bart Schelkens

Reputation: 1293

Writing unittest to create a file and then delete that file

I have this method I created :

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

Now I wrote the following unittest:

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

This test fails because the file is in use by a different proces. The test fails on het bool success = FileActions.DeleteFile(fileInfo); because the file is in use by a different process.

How can I change my test so it works ?

Upvotes: 3

Views: 15480

Answers (1)

Alireza Maddah
Alireza Maddah

Reputation: 5885

You have to call Dispose method on the FileStream object returned by the File.Create method to release the handle to that file:

[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 block provides a convenient syntax that ensures the Dispose method of an IDisposable object is get called after leaving the scope of the block even if an exception occurs. The equivalent to the above code could be re-written with try-finally block:

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

Upvotes: 8

Related Questions