IOException when deleting files in NUnit teardown methods
Now will you take a look at the following piece of code, dear?
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:
[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
Kommentar veröffentlichen