如何测试文件系统观察程序是否引发正确的事件

本文关键字:是否 事件 程序 观察 何测试 测试 文件系统 | 更新日期: 2023-09-27 17:56:32

我正在一项服务中使用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();
}