我有这个单元测试:
[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);
}
Run Code Online (Sandbox Code Playgroud)
当我在ProcessDbFile例程中找到这个部分时发生了什么:
if (File.Exists(path2))
_dbDropper.DropDb();
Run Code Online (Sandbox Code Playgroud)
然后转到这个:
public bool DropDbStub()
{
try
{
File.Delete(@"c:\dbdata\data.mdf");
}
catch
{
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我得到了另一个进程正在使用该文件的异常.
我想我的主要问题是单元测试是一个单独的过程吗?
如果我注释掉单元测试的前两行:
// if(!File.Exists(path2))// File.Create(path2);
我没有得到异常,即使文件已经存在,删除按计划发生,只有当我在单元测试中有前两行时(并且它确实跳转到Create行,不知何故单元测试似乎有锁定文件.我可以做些什么来克服这个问题,保持测试正常工作,如果文件已经存在则测试删除文件,如果文件已经存在则先创建它?
File.Create(path2) 打开一个您永远不会关闭的文件流.
你的代码应该是:
if (!File.Exists(path2))
File.Create(path2).Close();
Run Code Online (Sandbox Code Playgroud)