I have this unit test:
[Test]
public void ProcessDbFile_should_delete_file_if_it_exists_then_copy_new_file_to_same_location()
{
// used to create condition where file already exists
if (!File.Exists(path2))
File.Create(path2);
_dbInstaller.ProcessDbFile(path1);
File.Exists(path2).ShouldBe(true);
errorReceived.ShouldBe(null);
}
what's happening is when I get to this part inside the ProcessDbFile routine:
if (File.Exists(path2))
_dbDropper.DropDb();
which then goes to this:
public bool DropDbStub()
{
try
{
File.Delete(@"c:\dbdata\data.mdf");
}
catch
{
return false;
}
return true;
}
I get the exception that the file is being used by another process.
I guess my main question is the Unit Test a separate process?
If I comment out the first 2 lines of the unit test:
// if (!File.Exists(path2)) // File.Create(path2);
I do not get the exception, even if the file is there already, the deletion happens as planned, only when I have these first 2 lines in the unit tests (and it does jump into the Create line, somehow the unit test seems to have a lock on the file. What can I do to overcome this, to keep the test working as it should, which is to test deleting a file if it already exists, and to create it first if it didn't exist already?
File.Create(path2)
opens a stream to that file that you never close.
Your code should be:
if (!File.Exists(path2))
File.Create(path2).Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With