2012-08-30 26 views
0

我有以下的代码,我想测试:如何编写依赖文件系统事件的单元测试?

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测试,将做到以下几点:

  1. 创建一个目录
  2. 设置一个DirectoryProcessor
  3. 写一些文件到目录(通过File.WriteAllText()
  4. 检查DirectoryProcessor.SourceFileChanged已经ONC解雇e为在步骤3中添加的每个文件。

我试过这样做并在步骤3后添加Thread.Sleep(),但很难使超时正确。它正确地处理我写入目录的第一个文件,但不是第二个(并且超时设置为60秒)。即使我能以这种方式工作,这似乎是编写测试的可怕方式。

有没有人有一个很好的解决这个问题?

回答

0

如果您正在寻找测试使用这个类我的回答是不相关的另一个对象。

当我写单元测试来操作,我更喜欢使用ManualResetEvent的

单元测试将是这样的:

 ... 
    DirectoryProcessor.SourceFileChanged+=onChanged; 
    manualResetEvent.Reset(); 
    File.WriteAllText(); 
    var actual = manualResetEvent.WaitOne(MaxTimeout); 
    ... 

时ManualResetEvent的是ManualResetEvent的和MaxTimeout一些时间跨度(我的建议总是使用超时)。 我们现在缺少“调用onChanged”:

 private void onChanged(object sender, SourceEventArgs e) 
    { 
      manualResetEvent.Set(); 
    }  

我希望这是有益

+0

谢谢!我不熟悉ManualResetClass!总的来说,我认为文件系统嘲讽是进行单元测试的正确方法。我也喜欢写这些更多的集成测试,让我看看代码是如何工作的。 – Vinay

2

通常,您关心的是测试与文件系统的交互,并且不需要测试实际执行操作的框架类和方法。

如果您在类中引入了抽象层,那么您可以在单元测试中模拟文件系统,以验证交互是否正确,而无需实际操作文件系统。

在测试之外,“真实”实现调用这些框架方法来完成工作。

是,理论上你需要集成测试的是“真实”的实施,但它应该在实践中是低风险的,通过手工测试的几分钟没有受到太大的变化,和可核查的。如果您使用开源文件系统包装器,它可能包含那些测试,以便您放心。

How do you mock out the file system in C# for unit testing?

+0

所以,在这里你会推荐嘲讽了FileSystemWatcher类? – Vinay

相关问题