I am currently writing a Silverlight class library which I want to use in a project, and decided to try Test Driven Development for this class. This is a really nice way to work, and the Silverlight development team made this very easy by providing a unit test framework easy to integrate into Visual Studio 2008.
(Note: You cannot simply use the built-in unit test framework, because a non-Silverlight application cannot reference a Silverlight class library).
To find information about where to download and how to install the Silverlight unit test framework, check this post.
- Start by creating the Silverlight class library that you want to work on.
- In the same solution, in VS2008, create a Silverlight unit test application.
(note: Typically I name this test application [MyClassLibrary].Test where [MyClassLibrary] is the name of the class library you want to test).
- In the test application, add a reference to the Silverlight class library that you want to test.
- Do not add any test at this time!
- Right-click on the Silverlight test application and select “Set as Start-Up Project”.
- Run the application. Don’t worry about the test result so far.
- In the web browser, select the menu “View source”:
- Copy the whole HTML code.
- In Visual Studio, right-click on the Silverlight test application and choose “Add / New Item…”.
- Select a HTML page, rename it “index.html”.
- Select the whole HTML code in index.html and replace it with the HTML code you have in the clipboard.
- Modify the Silverlight control’s “source” attribute to prepend the “ClientBin” folder.
This step is needed because of the placement of the generated TestPage.html. This page is generated inside the ClientBin folder, as well as the XAP file. Since our index.html is located outside of the ClientBin folder, we need to update the “source” attribute. This is a one-time only operation
- Right click on “index.html” and select “Set as Start Page”.
There are a few caveats though:
Important: After you download the test code, make sure that you set “GalaSoft.SL.MyClassLibrary.Test” as startup project, and “index.html” as start page!!