One thing missing from the Microsoft Silverlight testing framework is Visual Studio integration. Because of this many people end up using the standard non-Silverlight MSTest framework to test their Silverlight code. At first this may sound a little balmy, however, Silverlight assemblies are byte code compatible with normal .NET assemblies and will quite happily run within CLR 2.0. There are a few things, however, you should be aware of:
- You can only make calls to APIs that do not require the underlying Silverlight core (agcore), so anything inheriting from DependencyObject is out, as is WCF.
- The [SecurityCritical] attribute is ignored, meaning that calls that would normally be prohibited within Silverlight can be made without resulting in a MethodAccessException.
The limitations described in point one may at first seem quite significant, however, if you are abstracting your UI logic using some flavour of MVVM, MVC, MVP, etc. you will more than likely find that your code does not fall into this category, and WCF calls in most cases should be mocked.
The advantage of running your tests within Visual Studio is that you do not need to run all of your tests for each test run, which is particularly useful if you are following a TDD approach. The downside of course is that you have to be confident that running your tests within this environment does not affect the outcome of your tests, its a trade off.
Creating the Test Project
In Visual Studio create a normal (non-Silverlight) test project.
(At iMeta we use the “Hybrid” prefix to indicate we are mixing Silverlight and .Net code).
Remove all references from the project except for the reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework
Re-add any required references but this time selecting Silverlight assemblies, usually located within “C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v3.0” and “C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries”