我有以下的代码,我想测试:如何编写依赖文件系统事件的单元测试?
public class DirectoryProcessor
{
public string DirectoryPath
{
get;
set;
}
private FileSystemWatcher watcher;
public event EventHandler<SourceEventArgs> SourceFileChanged;
protected virtual void OnSourceFileChanged(SourceEventArgs e)
{
EventHandler<SourceEventArgs> handler = SourceFileChanged;
if(handler != null)
{
handler(this, e);
}
}
public DirectoryProcessor(string directoryPath)
{
this.DirectoryPath = directoryPath;
this.watcher = new FileSystemWatcher(directoryPath);
this.watcher.Created += new FileSystemEventHandler(Created);
}
void Created(object sender, FileSystemEventArgs e)
{
// process the newly created file
// then raise my own event indicating that processing is done
OnSourceFileChanged(new SourceEventArgs(e.Name));
}
}
基本上,我想写一个NUnit测试,将做到以下几点:
- 创建一个目录
- 设置一个
DirectoryProcessor
- 写一些文件到目录(通过
File.WriteAllText()
) - 检查
DirectoryProcessor.SourceFileChanged
已经ONC解雇e为在步骤3中添加的每个文件。
我试过这样做并在步骤3后添加Thread.Sleep()
,但很难使超时正确。它正确地处理我写入目录的第一个文件,但不是第二个(并且超时设置为60秒)。即使我能以这种方式工作,这似乎是编写测试的可怕方式。
有没有人有一个很好的解决这个问题?
谢谢!我不熟悉ManualResetClass!总的来说,我认为文件系统嘲讽是进行单元测试的正确方法。我也喜欢写这些更多的集成测试,让我看看代码是如何工作的。 – Vinay