How to verify that FileSystemWatcher is raising the correct events?

I am using System.IO.FileSystemWatcher in one of my services. I want to check that when the file that is being tracked changes, I get a notification.

I thought about the background thread changing the file. In the test, I would join this topic. Then I can argue that the correct events are being raised. I could sign up for a callback to capture if the event was triggered.

I have not tested related threads, so I'm not sure if this is the best way to handle this, or if there are some built-in methods in Moq or MSpec that will help check.

+4
source share
1 answer

Moq or MSpec do not have anything specifically built in to help you do this, except for some interesting syntax or functions that will help you organize your test. I think you are on the right track.

I'm curious how your service provides file change notifications. Does he open them publicly for testing? Or is this FileSystemWatcher completely hidden inside the service? If the service does not just send notification of events up and down, you should extract the monitoring file so that it can be easily tested.

You can do this with .NET events or callbacks or something else. No matter how you do it, I would write a test something like this ...

 [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(); } 
+2
source

All Articles