IOException when deleting files in NUnit teardown methods

Now will you take a look at the following piece of code, dear?

[TestFixture]
public class FileSystemTests
{
private static readonly string testPath = "./Test";

[TestFixtureSetUp]
public void CreateTestSetEnvironment()
{
DirectoryInfo dir = new DirectoryInfo(testPath);
if (!dir.Exists)
{
dir.Create();
}
}

[TestFixtureTearDown]
public void DestroyTestSetEnvironment()
{
DirectoryInfo dir = new DirectoryInfo(testPath);
if (dir.Exists)
{
dir.Delete(true);
}
}

[TearDown]
public void DestroyTestEnvironment()
{
DirectoryInfo dir = new DirectoryInfo(testPath);
foreach ( FileInfo file in dir.GetFiles() )
{
file.Delete();
}
}

[Test]
public void Test()
{
FileInfo file = new FileInfo( string.Format( @"{0}\test.txt", testPath ));
file.Create();
Assert.IsTrue( file.Exists );
}
}

When I ran into IOExceptions in my unit tests, I extracted the matter in question into this neat little fixture. To cut this a little short, here's what happens:
- Test() succeeds
- TearDown runs into an IOException, saying test.txt is locked.
The solution to this was found here :
After the test has run, the objects pointing to files have no scope anymore, but they still exist in memory. Hence, there's still references to the files and you can't delete / move them.

What you have to do is remove the references by enforcing GC.Collect in the TearDowns:

public void DestroyTestSetEnvironment()
{
GC.Collect();
DirectoryInfo dir = new DirectoryInfo(testPath);
if (dir.Exists)
{
dir.Delete(true);
}
}

[TearDown]
public void DestroyTestEnvironment()
{
GC.Collect();
DirectoryInfo dir = new DirectoryInfo(testPath);
foreach ( FileInfo file in dir.GetFiles() )
{
file.Delete();
}
}

Kommentare

Beliebte Posts aus diesem Blog

Using AutoMapper for MVVM implementations

Deploying ClickOnce-applications in different environments without modifying the assembly identity

Preparing for and passing MCTS exam 70-536