c# - 单元测试 FileSystemWatcher : How to programatically fire a changed event?

标签 c# .net unit-testing filesystemwatcher

我有一个 FileSystemWatcher 监视目录的更改,当其中有一个新的 XML 文件时,它会解析该文件并对其执行一些操作。

我的项目中有一些示例 XML 文件,我将它们用于我编写的解析器的单元测试目的。

我正在寻找一种方法来使用示例 XML 文件来测试 FileSystemWatcher

是否可以通过编程方式创建事件(以某种方式涉及 XML 文件)以触发 FSW.Changed 事件?

最佳答案

我认为您在这里采用了错误的方法。

您不应该尝试直接对 FileSystemWatcher 类进行单元测试(您不能 - 您无法控制它!)。相反,您可以尝试以下操作:

1) 为 FileSystemWatcher 类编写一个包装类,将其功能委托(delegate)给 FileSystemWatcher 的一个实例。下面是一个方法和一个事件的示例,根据需要添加更多成员:

public class FileSystemWatcherWrapper
{
    private readonly FileSystemWatcher watcher;

    public event FileSystemEventHandler Changed;

    public FileSystemWatcherWrapper(FileSystemWatcher watcher)
    {
        this.watcher = watcher
        watcher.Changed += this.Changed;
    }

    public bool EnableRaisingEvents
    {
        get { return watcher.EnableRaisingEvents; }
        set { watcher.EnableRaisingEvents = value; }
    }
}

(注意 FileSystemWatcher 的实例是如何传递给类构造函数的;您可以在构建包装器时即时创建一个新实例)

2) 为类提取一个接口(interface):

public interface IFileSystemWatcherWrapper
{
    event FileSystemEventHandler Changed;
    bool EnableRaisingEvents { get; set; }
}

//and therefore...

public class FileSystemWatcherWrapper : IFileSystemWatcherWrapper

3) 让你的类依赖于接口(interface):

public class TheClassThatActsOnFilesystemChanges
{
    private readonly IFileSystemWatcherWrapper fileSystemWatcher;

    public TheClassThatActsOnFilesystemChanges(IFileSystemWatcherWrapper fileSystemWatcher)
    {
        this.fileSystemWatcher = fileSystemWatcher;

        fileSystemWatcher.Changed += (sender, args) =>
        {
            //Do something...
        };
    }
}

4) 在应用程序初始化时,使用任何依赖注入(inject)引擎实例化您的类,或者只是做穷人的注入(inject):

var theClass = new TheClassThatActsOnFilesystemChanges(
    new FileSystemWatcherWrapper(new FileSystemWatcher()));

5) 现在继续为 TheClassThatActsOnFilesystemChanges 编写单元测试,方法是创建一个模拟的 IFileSystemWatcherWrapper,它可以按照您的意愿触发事件!您可以为此使用任何模拟引擎,例如 Moq .

底线:

当您依赖于您无法控制和/或无法进行有意义的单元测试的类时,请使用适当的接口(interface)围绕它编写一个包装,并依赖于该接口(interface)。您的包装器非常薄,即使您不能对其进行单元测试也不会造成什么伤害,而您的客户端类现在可以进行适当的单元测试。

关于c# - 单元测试 FileSystemWatcher : How to programatically fire a changed event?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33254493/

相关文章:

c# - ClickOnce 应用程序抛出错误 "..requires assembly MySql.Data Version 6.5.4.0 be installed in the Global Assembly Cache (GAC) first."

.net - 为什么我需要 Econo JIT?

c# - Windows Azure 解决方案的最佳单元测试框架

c# - 使用 FetchXML 获取(强类型)相关实体

c# - 使用 WPF 在线程中加载图像

c# - 获取/设置私有(private)静态集合?

java - 带有mockito和多个返回值的模拟CSV阅读器

java - 设置后备存储位置

c# - Entity Framework 数据加载策略对比

c# - 'tag list'的WPF输入法