I’m working on a project where we are automating the notification of a project management system. The storage mechanism is all XML files, so we’re using the FileSystemWatcher. Since I wear a green Test-First wrist band I wanted to find a way to write this test-first.
The logic that we are working with is that when a notification is fired, we have to ensure that the file is on a watch list, and if it is, we bubble the notification up. The first test ensures that all notifications are bubbled up if there is no watch list:
[Fact]
public void CardWatcherFiresProjectCardChangeEventWhenFileCreated()
{
CardWatcher watcher = new CardWatcher(@"C:\");
bool projectCardChangedCalled = false;
watcher.ProjectCardChanged += delegate { projectCardChangedCalled = true; };
MethodInfo createdEvent = watcher.GetType().GetMethod("fileWatcher_Created", BindingFlags.NonPublic|BindingFlags.Instance);
System.IO.FileSystemEventArgs args = new System.IO.FileSystemEventArgs(System.IO.WatcherChangeTypes.Created, @"C:\", "test.xml");
createdEvent.Invoke(watcher, new object[] { null, args });
Assert.True(projectCardChangedCalled);
}
First, I wrapped the FileSystemWatcher in my own class so I can expose what I need. I then expose a domain event – ProjectCardChanged – which will be the actual event bubbled up to the application. I then register as a listener for the domain event, and fire the actual event the FileSystemWatcher will raise using reflection.
This allows me to remove dependencies on things like file systems until I really need them for integration tests. It is a little longer test than I like, but really allows a good flow to be created with keeping the tests going.