FileSystemWatcher无法使用单元测试

本文关键字:单元测试 FileSystemWatcher | 更新日期: 2023-09-27 18:24:38

我尝试这个简单的测试来使用FileSystemWatcher类但是OnFileChanged事件没有触发

    [Test]
    public void CanNotifyWhenFileChanged()
    {
        var watcher = new XMLWatcher(_path);
        watcher.StartWatching();
        AddXMLNodeTofile(_path);// change the file
        bool c = watcher.IsFileChanged;
        Assert.IsTrue(c);
    }

这是我的方法

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;
}

FileSystemWatcher无法使用单元测试

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

还要确保路径和您正在查看的文件夹相同。

您的测试可能在触发事件之前就已完成。我使用一个名为FluentAssertions的库来测试事件。