C# System.IO.Abstractions模拟文件删除
我正在测试一些文件是否被删除。这是我正在测试的代码C# System.IO.Abstractions模拟文件删除,c#,unit-testing,C#,Unit Testing,我正在测试一些文件是否被删除。这是我正在测试的代码 public void RemoveLogFiles() { MainLogic.LogMessage("** Performing Housekeeping **"); // Delete Old Logfiles string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); path += logs
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();
}
}
}
public void RemoveLogFiles()
{
MainLogic.LogMessage(“**执行内务**”);
//删除旧日志文件
string path=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
路径+=日志目录;
字符串[]文件=_fileSystem.Directory.GetFiles(路径);
int span=Project.Properties.Settings.Default.LogRetention*-1;
foreach(文件中的字符串文件)
{
FileInfoBase fi=(FileInfoBase)\ u fileSystem.FileInfo.FromFileName(文件);
if(fi.LastAccessTime
这是我的测试
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();
var mockDirectory=new Mock();
string path=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
path+=MainWindow.logs目录;
字符串file1=path+“\\test.log”;
字符串file2=path+“\\test2.log”;
mockDirectory.Setup(g=>g.GetFiles(path)).Returns(new[]{file1,file2});
var_fileSystem=new Mock();
_SetupGet(g=>g.Directory).Returns(mockDirectory.Object);
MainWindow=新的MainWindow(_fileSystem.Object);
window.RemoveLogFiles();
注释
- 我已经验证了模拟中的预期路径与prod中正在传递和将要传递的路径相同
GetFiles()
不返回任何内容,即使我模拟它返回test.log
和test2.log
您可以使用
It.IsAny()
与
DateTime.Now
的紧密耦合将导致调用模拟删除时出现问题。
//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
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);