Using NUnit with WPF

My regular stream of blog posts has recently slowed to a trickle.  I’ve been spending a lot of time on my project at work, and a considerable amount of that effort has gone into creating unit tests with the NUnit v2.4 framework.  In this blog post I share a few tips I have learned along the way about using NUnit with WPF.

First of all, it is important to know that WPF elements must be created on a thread which uses the Single Threaded Apartment (STA) model.  By default, NUnit uses worker threads with the Multithreaded Apartment (MTA) model to run your tests.  If you try to create an element/control in an NUnit test you will quickly see what I mean.

When I first encountered this issue I was working on my laptop in a coffeehouse without an Internet connection.  I spent far too long figuring out a solution which worked.  When I got home and searched for a solution, I immediately found this blog post.  That solution includes a nifty way of keeping an exception’s stack trace valid, so I ended up adopting the code in that post.  Keep in mind that not all testing frameworks use MTA threads to run your tests, so this might not be a problem for people out there creating WPF elements with other unit testing frameworks.

Another point of interest for folks who create unit tests for WPF classes is that the Application.Current property will return null when a unit test executes.  When your unit tests are running there is no Application instance with an active message pump churning away.  If you are testing code which relies on Application.Current then you should consider using dependency injection on that class, so that your test code can inject a dummy Application instance.

For example, you might want to do something like this for the class under test:

 NUnit with WPF (using IoC)

Classes in the application would use the parameter-less constructor, and the test code would use the constructor which accepts an Application instance.

Here is a blog post which contains many useful links related to unit testing WPF code:

Comments are closed.

%d bloggers like this: