我创建了这个方法:
public static bool DeleteFile(FileInfo fileInfo)
{
try
{
fileInfo.Delete();
return true;
}
catch (Exception exception)
{
LogManager.LogError(exception);
return false;
}
}
现在我写了以下单元测试:
[TestMethod]
public void DeleteFileSuccessFul()
{
string fileName = "c:\\Temp\\UnitTest3.txt";
FileInfo fileInfo = new FileInfo(fileName);
File.Create(Path.Combine(fileName));
bool success = FileActions.DeleteFile(fileInfo);
Assert.IsTrue(success);
}
此测试失败,因为该文件正由其他进程使用。 测试失败了het bool success = FileActions.DeleteFile(fileInfo);因为该文件正由另一个进程使用。
如何更改测试以使其有效?
答案 0 :(得分:6)
您必须在Dispose
方法返回的FileStream
对象上调用File.Create
方法来释放该文件的句柄:
[TestMethod]
public void DeleteFileSuccessFul()
{
string fileName = "c:\\Temp\\UnitTest3.txt";
FileInfo fileInfo = new FileInfo(fileName);
using (File.Create(Path.Combine(fileName)))
{
}
bool success = FileActions.DeleteFile(fileInfo);
Assert.IsTrue(success);
}
UPDATE: using
块提供了一种方便的语法,可确保在保留块的范围后调用Dispose
对象的IDisposable
方法如果发生异常。可以使用try-finally
块重写上述代码的等效代码:
[TestMethod]
public void DeleteFileSuccessFul()
{
string fileName = "c:\\Temp\\UnitTest3.txt";
FileInfo fileInfo = new FileInfo(fileName);
FileStream fileStream = null;
try
{
fileStream = File.Create(Path.Combine(fileName));
}
finally
{
if (fileStream != null)
fileStream.Dispose();
}
bool success = FileActions.DeleteFile(fileInfo);
Assert.IsTrue(success);
}