In order to get off the ground quickly, I chose Laurent Bugnion’s MVVM Light framework to build a test project around. MVVM Light provides a nice framework upon which to base a MVVM application, with some handy facilities for messaging and commands.
As I built up my test project, I was quite happy with everything. I had previously started building a test WinForms application which downloaded files over the internet in parallel. I used this same idea to test out WPF. In short order, I had a worker thread system downloading files from different servers. Each thread was updating model properties which fired PropertyChanged events to update a view’s progress bars. All of this worked straight away, without any of the WinForms worries about only triggering updates from the UI thread.
My first real problem cropped up when I started rounding out my test suite. In a bunch of tests for a certain class, I was registering with the MVVM Light Messenger to verify a message was fired. I could run all of the tests in this class one-by-one, and they would pass. I could run all of them together in Visual Studio’s debug mode, and they would all pass. But when I ran them all in release mode, the last test in the list would fail with a “Non-static method requires a target” exception. Ugh.
With some extensive googling, I came across an issue report on the MVVM Light codeplex page: http://mvvmlight.codeplex.com/workitem/7579. Here, it is suggested that stale message listeners can cause the Messenger to send a message to an object that’s already been garbage collected. When I had registered for messages in my test code, I had inadvertently triggered this behavior.
In order to prevent this from happening, I added a call to
Messenger.Default.Unregister<>(); in my test teardowns. My tests started running reliably. Huzzah!
The Messenger system in MVVM Light is pretty nice. It’s quite flexible, and provides a good way to loosely couple components. This behavior really tripped me up, though.