Thursday, November 1, 2012

Unit Testing a Windows 8 Application

I am a big fan of test driving an application. That's why I write almost no code without writing a test for it.

I recently began writing a Windows Store application for Windows 8 and again wanted to test drive this app.   If you look at MSDN at how to add a test project to you Windows 8 app, you will see, you can add a Windows Store test project to your solution. Now, handy as this is, the down sight is that this test project is as well a Windows Store project type, meaning you won't be able to add a whole bunch of references to it. I wasn't able to add RhinoMock or Moq to it, nor was I able to add MSpec. The problem being these frameworks were build to the wrong version of the .Net framework.

Now, I could have made my own builds of the frameworks I am happy working with, but I started looking if there is no other way, like using a simple class library for unit testing a Windows Store app. Now, when you try this, the problem is, you can't get a reference of your Windows Store app added to your class library for testing.

To get this fixed, I tried out a couple of things. First I tried adding the same references to my class library project as were in the Unit Test Library for Windows Store apps. This didn't work, however. Also, I couldn't find the '.NET for Windows Store apps' reference dll. I also tried playing around with the output type of my project. Changing it to something different than class library. But then again, adding the necessary unit testing references became a problem. I also played around with the conditional compilation symbols (hey, I was trying to find where the differences lay between my own class library and a Unit Test Library for Windows Store apps).

After trying all that, I unloaded my project from solution explorer and started editing it, comparing it to the Unit Test Library for Windows Store apps and trying out different combinations. Now, after a couple of tries, the setting in your project file, you need is the following:

<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />

You can put this line as a replacement of the other csharp.targets file at the bottom of your project file. Once you have added this, you can add a reference of your Windows Store app to your class library. You will even see the '.NET for Windows Store apps' reference show up in your references. You will even be able to add all the additional references you want, like NUnit, Moq or RhinoMock, ...

One additional problem I had was with the System.Data dll, which was build to a different framework. Since I didn't need it in my test project, I happily removed it.