2013-07-24 79 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));' –