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

标签 c# multithreading unit-testing 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();
}

关于c# - 我如何测试 FileSystemWatcher 引发正确的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579362/

相关文章:

c# - 异常 : The given filter must implement one or more of the following filter interfaces when implementing custom filter in WebAPI 2

c# - 如果值为 NULL,为什么 nullable int (int?) 不会通过 "+="增加值?

java - 如何避免 JFrame.EXIT_ON_CLOSE 并优雅地终止 swing 程序

c# - 如何使用 Moq Azure Key Vault 进行单元测试

c# - 单元测试 Mvc.Compare 属性错误地返回模型 isValid = true

c# - Ninject 基于约定的绑定(bind)将在运行时解析

windows - 如何让调试器强制 Windows 线程从 sleep 状态唤醒?

c++ - qt中线程的使用方法

python - 如何在 python 中对 POST 方法进行单元测试?

c# - 未标记为符合 CLS 的程序集的实际限制?