In this post, I explain how you can unit-test your Silverlight and Windows Phone 7 class libraries using MSTest and the built-in test system of VS2010, enabling you to right-click a test to run it.
I am a test driven developer, and simply hate the testing harnesses available to SilverLight (SL) and Phone 7 (wp7) development enviroments. I do believe that Microsoft should make it a priority to allow MSTest to execute the class libraries written for other language runtimes than the CLR in windows, but that is a side issue.
Today I bring you my proposal for a workaround.
I wrote a helloWorld application for wp7, and downloaded Roger Peterâ€™s cheat sheet for unit testing apps this platform. The stuff does work, but looks highly impractical in my view â€“ mostly due to the lack of screen estate, but also because it does not integrate with the Visual Studio 2010 test harness.
The key is in the link
The trick to getting your logic tested is to link the source files into a new, regular window class library project. Hereâ€™s the recepy:
- Hatch an idea for a wp7 app (or SL) with the potential to rule the world (donâ€™t they all?)
- Create a solution for your application, and add a wp7 Project
- Add another wp7 project for your tests
- Create a regular Windows Class Library and choose to add existing item. Pay close attention to the drop-down arrow on the ADD button. Use this to select â€œAdd as Linkâ€
- Do this for all the classes that you wish to test
Within your project, you should see the linked files marked with a small arrow, marking it as linked:
It mostly works!
Having done this, you now have a regular windows class library that you can use to unit test the logic of your application using MSTest. As an added bonus, should you want to create a wpf applicaton later, you can, of course, re-use code in this way for cross-target platform work.
Changes done to the linked file happen only in the original file, so you can now drive the logic in your class file with unit tests by using your unit testing framework of preference.
Why it has a smell to it
This is still somewhat smelly workaround, consider that you cannot unit-test wp7/SL specific functionality. It is only a workaround that applies to code that compiles to windows and wp7/SL at the same time. Having said that â€“ if you follow the SOLID principles, you should not have any problems unit-testing most of your code, it would only be the platform specific parts and GUI that you leave to the lacking test harness, for those you can safely use the recommended test harnesses, such as the one proposed by Roger Peter.
The perfect solution would, of course be to have MSTest support these other runtimes as a silent simulator or something.