Windows Phone From Scratch #41
There has been some confusion about how to make the Silverlight Unit Tests work on Windows Phone. The latest release of the Silverlight Unit Tests comes with the Silverlight Toolkit, and it targeted at Silverlight 4. Windows Phone is based on an enhanced version of Silverlight 3 and cannot use these DLLs.
Fortunately, Jeff Willcox has made the right DLLs available on his web site.
Silverlight 3 binaries for the Silverlight Unit Test Framework
You will need to ‘unblock’ the zip file before unpacking the files. These binaries are strong named, but are not Authenticode signed, so they are not official
To get started, follow these steps:
- Make sure Visual Studio 2010 is installed
- Download, unblock and install the Silverlight Unit Tests
- Create a new Windows Phone project
- Add references to the two DLLs
- Microsoft.Silverlight.Testing
- Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight
- Be sure to put the unit tests inside the same project as the project you are testing, though it is good programming practice to isolate the tests in their own folder and namespace.
- Be sure to add using statements in each file that must recognize the testing framework (certainly in mainpage.xaml.cs) for the two DLLs
using Microsoft.Phone.Controls; using Microsoft.Silverlight.Testing;
Jeff Willcox has provided the following excellent way to turn on and off the unit testing by flipping a boolean in MainPage.xaml.
public MainPage( ) { InitializeComponent( ); const bool runUnitTests = true; if ( runUnitTests ) { Content = UnitTestSystem.CreateTestPage( ); IMobileTestPage imtp = Content as IMobileTestPage; if ( imtp != null ) { BackKeyPress += ( x, xe ) => xe.Cancel = imtp.NavigateBack( ); } } }
In essence, if the boolean is true, then the unit tests become the content of the main page.
For an excellent step by step walk through on creating your first unit tests, I highly recommend David Gadd’s tutorial Building a Windows Phone 7 app with MVVM pattern, using TDD and mock objects
Thanks for pointing out the possibility to run unit tests for WP7, this is going to be very useful for getting quality apps developed. But can I ask you to make a blog post about WP7 and CI?
My problem is that there is no SDK to install on the CI server and I don’t want to have to install the full WP7 development suite on my build server. I’ve tried copying across the build targets but it’s not really a practical way. It would be nicer if there were an SDK to install so the build server could build and continuously verify the project.