我对测试相对较新,并且仍然围绕着一些基础知识。我有一个方法,我想测试哪个基本上创建一个不同的文件名,如果提供已存在(我已粘贴下面的代码)。
我需要一种测试方法,如果文件已经存在,该方法会返回一个不同的(但也是唯一的)名称。在Visual Studio的单元测试中测试这个的最佳方法是什么?是创建一个文件作为测试的一部分然后删除它还是有更好的方法?
public static FileInfo SafeFileName(this FileInfo value)
{
if (value == null) throw new ArgumentNullException("value");
FileInfo fi = value;
//Check the directory exists -if it doesn't create it as we won't move out of this dir
if (!fi.Directory.Exists)
fi.Directory.Create();
//It does so create a new name
int counter = 1;
string pathStub = Path.Combine(fi.Directory.FullName, fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));
// Keep renaming it until we have a safe filename
while (fi.Exists)
fi = new FileInfo(String.Concat(pathStub, "_", counter++, fi.Extension));
return fi;
}
答案 0 :(得分:3)
答案 1 :(得分:2)
以下是两种测试方法(使用Visual Studio单元测试项目):
// using System.IO;
[TestMethod]
public void WhenFileExists()
{
// Create a file
string existingFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
using (File.Open(existingFilename, FileMode.CreateNew)) { }
// Check its existence
Assert.IsTrue(File.Exists(existingFilename));
// Call method to be tested
string newFilename = DummyCreateFile(existingFilename);
// Check filenames are different
Assert.AreNotEqual<string>(existingFilename, newFilename);
// Check the new file exists
Assert.IsTrue(File.Exists(newFilename));
}
[TestMethod]
public void WhenFileDoesNotExist()
{
// Get a filename but do not create it yet
string existingFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
// Check the file does not exist
Assert.IsFalse(File.Exists(existingFilename));
// Call method to be tested
string newFilename = DummyCreateFile(existingFilename);
// Check the file was created with the filename passed as parameter
Assert.AreEqual<string>(existingFilename, newFilename);
// Check the new file exists
Assert.IsTrue(File.Exists(newFilename));
}
private string DummyCreateFile(string filename)
{
try
{
using (File.Open(filename, FileMode.CreateNew)) { }
return filename;
}
catch
{
string newFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
using (File.Open(newFilename, FileMode.CreateNew)) { }
return newFilename;
}
}
测试方法略有改变,因为它简单地采用(并返回)字符串参数而不是FileInfo。
答案 2 :(得分:0)
使用File.Exists方法。