我认为你在这里采取了错误的方法。
您不应该尝试直接对FileSystemWatcher 类进行单元测试(您不能——您无法控制它!)。相反,您可以尝试以下方法:
1) 为FileSystemWatcher 类编写一个仅 将其功能委托给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) 提取类的接口:
public interface IFileSystemWatcherWrapper
{
event FileSystemEventHandler Changed;
bool EnableRaisingEvents { get; set; }
}
//and therefore...
public class FileSystemWatcherWrapper : IFileSystemWatcherWrapper
3) 让你的类依赖于接口:
public class TheClassThatActsOnFilesystemChanges
{
private readonly IFileSystemWatcherWrapper fileSystemWatcher;
public TheClassThatActsOnFilesystemChanges(IFileSystemWatcherWrapper fileSystemWatcher)
{
this.fileSystemWatcher = fileSystemWatcher;
fileSystemWatcher.Changed += (sender, args) =>
{
//Do something...
};
}
}
4) 在应用程序初始化时,使用任何依赖注入引擎来实例化你的类,或者只是做穷人的注入:
var theClass = new TheClassThatActsOnFilesystemChanges(
new FileSystemWatcherWrapper(new FileSystemWatcher()));
5) 现在继续为TheClassThatActsOnFilesystemChanges 编写单元测试,方法是创建一个IFileSystemWatcherWrapper 的模拟,它可以随意触发事件!您可以为此使用任何模拟引擎,例如Moq。
底线:
当您依赖于您无法控制和/或无法进行有意义的单元测试的类时,请使用适当的接口对其进行包装,并依赖于该接口。您的包装器非常薄,如果您不能对其进行单元测试,它不会真正受到伤害,而您的客户端类现在可以正确地进行单元测试。