2013-07-24 82 views
0

我试试这个简单的测试与 FileSystemWatcher类,但不点火FileSystemWatcher的不与单元测试工作

[Test] 
    public void CanNotifyWhenFileChanged() 
    { 

     var watcher = new XMLWatcher(_path); 
     watcher.StartWatching(); 
     AddXMLNodeTofile(_path);// change the file 
     bool c = watcher.IsFileChanged; 
     Assert.IsTrue(c); 

    } 

的OnFileChanged事件工作,这是我的方法

public void StartWatching() 
{ 
    var watcher = new FileSystemWatcher 
         { 
          Path = 
          Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), 
          IncludeSubdirectories = false, 
          NotifyFilter = NotifyFilters.LastAccess | 
             NotifyFilters.LastWrite | 
             NotifyFilters.FileName | 
             NotifyFilters.DirectoryName, 
          Filter = FilePath 
         }; 

    watcher.Changed += OnFileChanged; 
    watcher.EnableRaisingEvents = true; 

} 
+2

你确定'_path'和'GetExecutingAssembly()。Location'的结尾足够相似,FSW应该调用一个事件吗? –

+0

@Damien_The_Unbeliever非常感谢您这是问题 – tito11

+0

@Damien_The_Unbeliever请将您的评论添加为答案:) – tito11

回答

3

请注意,某些单元测试运行程序(NUnit,MSTest)会对文件执行影子复制,即在执行之前将测试二进制文件复制到单独的位置。因此,您的测试程序集驻留的_path和路径可能不一样。

还要确保_path和您正在观看的文件夹是相同的。

1

你的测试可能完成在事件被解雇之前。我使用名为FluentAssertions的库来测试事件。

+0

如果Tim所说的是真实的话,请尝试将您的断言封装在SpinWait中。 SpinWait.SpinUntil(()=> myPredicate(),10000) –

+2

实际上,NUnit延迟了断言'Assert.That(c,Is.True.After(delayInMilliseconds));' –