Silverlight Unit Testing With NUnit: yes you can
Join the DZone community and get the full member experience.Join For Free
It may be obvious for most of you, but it took a while to my caveman brain to realize this, so I figured I could post it for other cavemen. You (we) have got an excuse though: the short release cycle of Silverlight means that most stackoverflow questions and blog posts on the subject are out-of-date and refer to older versions of Silverlight (<=3) when what I describe was not possible.
Up to Silverlight 3 you had to use a Silverlight-specific unit testing tool, like the Silverlight Toolkit framework. These tools are quite awesome and have been fundamental, but it’s nice to have the full power of NUnit (or xUnit & co.) at disposal. In addition to the community and tooling support, it’s practical to use the same tool you already use for other .NET projects.
The game changer is called binary assembly compatibility, brought by Silverlight 4. In a few words this means that you can add a reference to a Silverlight assembly from a “full” .NET project (provided that you don’t use any Silverlight-only class).
If your application is correctly layered (for ex. with MVVM) in most cases it’s trivial to keep views and viewModels/models in separate assemblies. ViewModels and models usually don’t reference any Silverlight-only class (otherwise you may have a code smell!) and are 100% compatible with .NET, so testing them with NUnit is as easy as
- create a .NET class library in your solution
- add a reference to NUnit (NuGet it!)
- add a reference to your model and/or viewModel assemblies
- write your unit tests
- run them with NUnit
no tweaking or hacking required and works fine with F# assemblies as well.
It is typical for views to use Silverlight-only classes, but this is generally not a problem because it doesn’t make much sense to unit-test them anyways as they are mostly XAML with very little amounts of code-behind.
Free tip: if you want to test internal classes and methods you can add the InternalsVisibleTo attribute to the target assembly.
Published at DZone with permission of Francesco De Vittori, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.