[英]System.IO.Abstractions Mock File Delete
我正在尝试测试是否删除了某些文件。 这是我正在测试的代码。
public void RemoveLogFiles()
{
MainLogic.LogMessage("** Performing Housekeeping **");
// Delete Old Logfiles
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
path += logsDirectory;
string[] files = _fileSystem.Directory.GetFiles(path);
int span = Project.Properties.Settings.Default.LogRetention * -1;
foreach (string file in files)
{
FileInfoBase fi = (FileInfoBase)_fileSystem.FileInfo.FromFileName(file);
if (fi.LastAccessTime < DateTime.Now.AddDays(span))
{
MainLogic.LogMessage("Delete " + fi.FullName);
fi.Delete();
}
}
}
这是我的测试。
var mockDirectory = new Mock<IDirectory>();
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
path += MainWindow.logsDirectory;
string file1 = path + "\\test.log";
string file2 = path + "\\test2.log";
mockDirectory.Setup(g => g.GetFiles(path)).Returns(new[] { file1, file2 });
var _fileSystem = new Mock<IFileSystem>();
_fileSystem.SetupGet(g => g.Directory).Returns(mockDirectory.Object);
MainWindow window = new MainWindow(_fileSystem.Object);
window.RemoveLogFiles();
笔记
问题/问题
GetFiles()
不返回任何东西,即使我已经模拟它返回test.log
和test2.log
。
我还需要模拟文件还是有更好的方法来测试文件删除?
您可以使用It.IsAny<string>()
设置更宽松的期望
//Arrange
string[] files = new[] { file1, file2 };
var _fileSystem = new Mock<IFileSystem>();
_fileSystem
.Setup(_ => _.Directory.GetFiles(It.IsAny<string>())
.Returns(files);
//... still need to setup file info for
//... _fileSystem.FileInfo.FromFileName(file)
MainWindow window = new MainWindow(_fileSystem.Object);
//Act
window.RemoveLogFiles();
//Assert
看看它的行为是否符合预期。
如果确实如此,则path
存在问题。
我是否也需要模拟文件
是的,如果您希望被测主题按预期完成。
最后,我还建议在构建文件路径时使用Path.Combine
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
path = Path.Combine(path, logsDirectory);
// or single line
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop, logsDirectory);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.