Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过单元测试使用File.Create和Delete,但得到;“其他流程使用的文件”;例外_C#_File Io - Fatal编程技术网

C# 通过单元测试使用File.Create和Delete,但得到;“其他流程使用的文件”;例外

C# 通过单元测试使用File.Create和Delete,但得到;“其他流程使用的文件”;例外,c#,file-io,C#,File Io,我有一个单元测试: [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);

我有一个单元测试:

   [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);
   }
当我进入ProcessDbFile例程中的这一部分时,会发生什么:

   if (File.Exists(path2))
       _dbDropper.DropDb();
然后是这样的:

public bool DropDbStub()
{
   try
   {
      File.Delete(@"c:\dbdata\data.mdf");
   }
   catch
   {
      return false;
   }
  return true;
}
我得到一个例外,该文件正被另一个进程使用

我想我的主要问题是单元测试是一个独立的过程吗

如果我注释掉单元测试的前两行:

   [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);
   }
//如果(!File.Exists(路径2)) //创建(路径2)

我没有得到异常,即使文件已经存在,删除也会按计划进行,只有当我在单元测试中有前两行时(它确实跳入了创建行,不知何故,单元测试似乎锁定了文件。我该怎么做才能克服这个问题,让测试正常工作,即测试删除一个已经存在的文件,如果它还不存在,则首先创建它?

file.Create(路径2)
打开一个指向该文件的流,您永远不会关闭该流

您的代码应该是:

if (!File.Exists(path2))
    File.Create(path2).Close();