c# – 如何测试FileSystemWatcher引发正确的事件?

我在我的一个服务中使用System.IO.FileSystemWatcher.我想测试当被监视的文件发生变化时,我会收到通知.

我正在考虑让后台线程更改文件.在测试中,我会加入该线程.然后我可以断言调用了正确的事件.我可以订阅一个回调来捕获事件是否被调用.

我没有做任何涉及线程的测试,所以我不确定这是否是处理它的最佳方式,或者是否有一些内置的方式在Moq或MSpec中有助于测试.

最佳答案 除了一些有助于组织测试的有趣语法或功能外,Moq或MSpec没有专门内置的任何内容可帮助您完成此操作.我认为你走的是正确的道路.

我很好奇您的服务如何公开文件更改通知.是否公开公开测试?或者FileSystemWatcher是否完全隐藏在服务中?如果服务不是简单地向上和向外传递事件通知,则应提取文件监视以便可以轻松测试.

您可以使用.NET事件或回调或其他任何操作.无论你怎么做,我都会写这样的测试…

[Subject("File monitoring")]
public class When_a_monitored_file_is_changed
{
    Establish context = () => 
    {
        // depending on your service file monitor design, you would
        // attach to your notification
        _monitor.FileChanged += () => _changed.Set();

        // or pass your callback in
        _monitor = new ServiceMonitor(() => _changed.Set());
    }

    Because of = () => // modify the monitored file;

    // Wait a reasonable amount of time for the notification to fire, but not too long that your test is a burden
    It should_raise_the_file_changed_event = () => _changed.WaitOne(TimeSpan.FromMilliseconds(100)).ShouldBeTrue();

    private static readonly ManualResetEvent _changed = new ManualResetEvent();
}
点赞