15 May, 2011

WP7: How to unit-test your ViewModels when using MVVM

For this to work, you need to install the NUnit Silverlight Framework.You can download the .vsi-file from here: http://www.testdriven.net/downloads/SilverlightNUnitProject.zip

This will give you this project template:



It has always been a source of great frustration for me with Silverlight, WP7 and unit testing in combination. It has remained an unsolved mystery to me why this is not possible with the native UnitTesting framework from Microsoft to author and run unit tests against your viewmodels? Come on, they are just plain assemblies (dll).

I know a specific Silverlight Unittesting framework has emerged, but I want to use the code-friendly unit testing experience that I’m used to inside Visual Studio. I don’t want to be unittesting in the phone emulator!

Anyway – forced to start using an old-time friend (NUnit) in my current work situation has actually solved the problem it seems. NUnit does not care what assemblies it is to load; it just loads them and applies the unit-test you specify! Therefore – you can use NUnit to perform the VM-unittesting you wish.

But, this requires an external GUI for running Unit tests, you might state? That is not entirely correct; an external GUI testrunner does exist, but you can also download Visual NUnit (see screenshot) from the Online Gallery inside Visual Studio. This runner can be nicely placed in your righthand side toolbox and will allow you to run unittests as easy as any other (Microsoft) framework you might think of.

Visual NUnit

The quality of these unit-tests is not dependent on what framework you are using, but on your own code.

So this is actually the way to do unit-testing of the ViewModel in a MVVM-application for the WP7 phone…

Happy coding.


Yauhen Safrankou said...

Great stuff! Downloaded, installed and started to write unit tests against MVVM models for WP7 application. Just had to change the target framework to .NET 4, as I already updated to Mango bits. Run tests with R#. Everything works. Thanks!

Mikael Koskinen said...

Thanks for the tip. I have previously used this with great success but now with ReSharper 6 the unit test runner doesn't like to execute the tests. The tests just stay gray.

Have you guys noticed the same?

Stefan Lieser said...

Same problem here: with R# 6 the WP7/NUnit Tests stay gray :-(

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...