I am starting a short series of posts on unit testing of Silverlight applications. I will be using the following set of technologies.
- Microsoft Silverlight Unit testing framework that ships with Silverlight tool kit
- Moq – mocking framework that supports Silverlight 4
- StatLight – unit testing automation framework that will allow for unattended / automated running unit tests
I am going to start with a simple Silverlight application that is using RIA services and Prism. First things first, let’s create unit test project. Project template will be installed when you install the Silverlight toolkit. Here is what add project dialog looks like. The template is located under Silverlight tab
Here are the setting for the next dialog:
Once project is created, a simple test class is also created. If you ever worked with Microsoft unit testing in Visual Studio, you will find the API quite familiar, including all key classed, attributes and namespaces. I am going to create a simple synchronous test first, testing my RIA services class to ensure that validation rules are setup properly. To do so, I first add a reference to my simple Company module to my Silverlight unit test project. Since I am also testing RIA services classes, I will add two more references: System.ComponentModel.DataAnnotations and System.ServiceModel.DomainServices.Client.dll. Now with this our of the way, here is what my test class and method look like:
public class Tests
public void TestCompanyRules()
Company company = new Company();
company.CompanyName = "test";
Assert.AreEqual(0, company.ValidationErrors.Count, "Should be valid");
company.CompanyName = string.Empty;
Assert.AreEqual(1, company.ValidationErrors.Count, "Should be in valid");
Let me go over the attributes I used. TestClass attribute is what signals to Unit testing framework as to what classes contain unit tests. TestMethod attribute identifies methods that represent a single unit test. Tag attribute is used by unit test runner UI to filter out what tests based on attributes will be run. Description attribute data will be shown in runner UI when unit tests are run. Assert class is used to assert test results. For example, in my first Assert statement I make sure that Company instance is valid once name is set.
When I run unit tests after setting up unit test application’s web site as start up project, here is what I see.
Test are setup to auto-run by default. You will see the countdown label, and if you click on count down label, you will have a chance to select specific tests to run.
After tests are run, you will see test run summary in the top left cornet of the screen. In my case I see that I had total of 1 test, and 2 test has passed. if a test fails, you will see that in the test run summary. You can download solution so far here. In my next post I will cover asynchronous testing in Silverlight application.