Silverlight Best Practices: Testing Soup to Nuts
Silverlight poses several unique challenges for testing. The Silverlight runtime is not integrated into Visual Studio, so it is not possible to run Silverlight unit tests out of the box using the Visual Studio Test System (VSTS) that is built in. There are some extensions and methods to make this happen, but it’s not as straightforward as generating unit tests for desktop and server code. Silverlight also depends on a plugin to execute in the browser, so it does not expose the standard HTML that web automation tools are built to look for. Creating automated UI tests involves building your application a certain way to provide accessibility hooks that the test system can use to interact with your application.
There are many reasons why you should test your Silverlight applications that are covered in detail in my upcoming Addison_Wesley Professional book, Designing Silverlight Business Applications. The advantages of testing include:
- Testing eliminates assumptions
- Testing kills bugs at the source
- Testing helps document code
- Testing makes extending and maintaining applications easier
- Testing improves architecture and design
- Testing makes better developers
There are various flavors of tests. In this article, you will learn how to build unit tests using two different methods as well as how to create coded-UI tests that mimic user interaction.
Unit Tests
Unit tests are a category of tests known as “white box” tests. The entire software system can be looked at two ways. The end users see a “black box” because they are not exposed to the source code, database definitions, and other processes that drive the application. Instead, they are aware of interactions (most often directly through the user interface) that go into a black box, and results that come out of that black box. This is the realm of QA and automated UI tests.
“White box” tests would be better referred to as “clear box” tests because they imply exposure to the inner workings of the system. Unit tests require a fundamental knowledge of what’s happening at the source code and stored procedure level. Integration tests require knowledge of the APIs and boundaries between systems. White box tests ensure the internal system is working and is the set of “checks and balances” that keeps the black box functioning correctly.
Properly written unit tests follow a very specific set of guidelines. They focus on a very specific function of a class. They should be written without dependencies so they can run in the absence of web services and backend databases. They should be short and simple, which reflects upon the class design because it’s tough to write simple tests for overly complicated methods. The unit tests should be easy to write. If not, it’s a sign the target class may need refactoring.
Silverlight Unit Testing Framework
Silverlight does not directly integrate directly with the VSTS. You are not able to create a test project and run the tests using the “Test Window” within Visual Studio. Fortunately there exists a framework for testing Silverlight projects called the Silverlight Unit Testing Framework. The framework is included as part of the Silverlight Toolkit and is designed to run unit tests in the browser.
To obtain the testing framework, install the latest Silverlight Toolkit. The toolkit will add a new project template for Silverlight. To create a test project, add a new project and select the “Silverlight Unit Test Application” template. The template will add references to a set of DLLs that provide the test harness. You can see the harness being used inside the App.xaml.cs that is created with the test project. The root visual is set by the following line of code:
RootVisual = UnitTestSystem.CreateTestPage();
This is the “test harness” for the Silverlight Unit Testing Framework. The framework works by allowing you to build unit tests, then run them in a Silverlight application. The tests use an attribute module that mirrors the one used by the VSTS. The attributes exist in the following namespace:
Microsoft.VisualStudio.TestTools.UnitTesting;
Unit test classes are tagged with the TestClass attribute. You set up the test in a method tagged with the TestInitialize attribute and clean them up using TestCleanup. Test methods are flagged using the TestMethod attribute.
Here is an example test class with a method that will always pass:
namespace MyTestProject { [TestClass] Public class MyTest { [TestMethod] public void NeverFails() { Assert.IsTrue(true); } } }
When you compile and run the application, you will see a browser window open with a list of tests. The left pane includes test classes and methods, while the right pane provides a list of results. Any tests that fail are flagged in red and provide the failure details in the right panel.
It is possible to tag tests using the Tag attribute to categorize them. For example, if you have separate modules, you might tag all tests for a specific module with the module name. You will then be able to run tests specifically for that module without having to run the other tests in the solution. To test for exceptions, simply add the ExpectedException attribute to the test method. If the specified exception is thrown, the test harness will capture it and pass the test. If it is not thrown, the test will fail.
You can read about more advanced features in the documentation. The main disadvantage to using the Silverlight Unit Testing Framework is that it requires the browser to run and is not automated out of the box. If you require automated testing (i.e., tests that run on a build box without user interaction), you have two options. You can extend the Silverlight Unit Testing Framework using projects like StatLight, or you can share your Silverlight code and run tests using VSTS.
Linked Classes/Shared Testing with VSTS
Silverlight code written using the best practices detailed in this series should isolate business logic from presentation logic using the MVVM pattern. The view models and other classes in your project should not have Silverlight-specific dependencies on view elements or other APIs that do not exist in the .NET Framework. This makes it possible to share the Silverlight code with a traditional test project and unit test it using the built-in test system in Visual Studio.
To use this approach, create a C# test project (using the built-in test templates and not the Silverlight Unit Testing Framework). Create a folder to hold shared code. Right-click on the folder and choose Add Existing Item, then browse to an existing Silverlight class you wish to test. Notice that the Add button in the lower right is actually a drop-down. Expand the drop-down and choose the option Add as Link. This will create a link so that any updates you make in your Silverlight project will be reflected in your test project. Repeat this for the various classes you wish to test.
After the classes are added, you can build the project to confirm they compile in the .NET Framework and then begin adding your tests. Creating tests in this fashion is no different than traditional methods and can be connected to any type of automated testing utility or extension that works with VSTS, including Team Foundation System (TFS).
Automated UI Testing
The Silverlight UI is driven by XAML and data-binding. Data-binding allows for highly decoupled code but does introduce some indirect dependencies. The data-binding statement itself depends on an implicit contract. That contract contains the paths and names of the properties being bound to. If the designer accidently changes the name or path of a data-binding, it can cause the binding to fail at runtime. Testing is one way to ensure the contract remains intact.
XAML Testing
The first method for testing XAML is to use a technique called XAML Testing. This technique uses the Silverlight Unit Testing Framework. When your test class derives from the SilverlightTest base class, you are provided with a TestPanel that you can add visual elements to. In the test class, you create a copy of the view and then bind a view model, either by creating a direct instance or using a mock. Mark the test as asynchronous, add the view to the panel and hook into the Loaded event. After the view is loaded, you can test both directions of bindings. You can find an element, set a value and verify it has updated the corresponding property in the view model, and you can set a property on the view model, find the corresponding element in the view, and verify that its value has changed.
Coded UI Tests
Coded UI tests are a special form of test offered by the Visual Studio test system. They allow you to record actions during a session with your application and then play them back. The idea is that the path through your application should remain consistent and function appropriately as the application evolves, so the test can capture when a change inadvertently impacts the UI. In some cases, you may expect the test to fail so that you can record a new path through the application.
There are several challenges with automating testing of Silverlight applications. While Silverlight can run inside of the browser, it is not HTML and therefore does not provide the same Document Object Model (DOM) that an HTML page does. Many testing tools simply don’t recognize the Silverlight application because it exists inside the context of a plugin that runs inside of the browser. For this reason, some automation tools don’t work directly with Silverlight.
Another challenge with coded UI tests for Silverlight is that the support does not exist “out of the box” in Visual Studio 2010. To support coded UI testing, you must first install the Visual Studio Feature Pack 2. The feature pack is only available if you have a valid MSDN subscription. You can download the feature pack from this link.
For coded UI tests, you must update the project to include the reference for coded UI testing. Adding the reference is another challenge because the DLL is only for testing and must be removed from your XAP file when in production. Adding it conditionally involves editing the project file directly. The MSDN page for creating Silverlight coded UI tests explains this in detail. You must also ensure that your controls have unique automation properties. This is a special property used in automation and there is an MSDN page that describes how to assign unique identifiers.
Once you have the prerequisites set up, you can begin testing. Testing is hosted by a standard Visual C# test project (not the Silverlight Unit Testing Framework). Add the project then add a new “Coded UI Test.” This will open a dialog to generate the code for your test. Choose the option to “Record actions” and a small panel will appear with the option to start recording. At this point, you should know what the local URL for your Silverlight project is. You can determine that by running the Silverlight project and noting the URL in the browser.
Launch Internet Explorer and navigate through the application. Click a button, enter text, and perform other functions that a user would ordinarily make in the course of using the application. When you are finished, close Internet Explorer and click the Generate Code button on the UI control. Provide a method name and choose Add and Generate to generate the method that uses automation to walk the Silverlight project. Once complete, you will have a complete test. If you run the test from Visual Studio, it will launch Internet Explorer and your Silverlight application and perform the recorded actions. If any fail or the expected results are not found, it will fail the test.
Summary
Testing is an important part of maintaining line-of-business applications. Silverlight applications are no exception, and there are several methods you can use to ensure they are properly tested. This article focused on the built-in methods provided by Visual Studio. There are also many third-party solutions designed specifically for generating and running tests against Silverlight applications. Regardless of your needs, you will be able to create the appropriate tests to ensure stable, maintainable, and extensible line-of-business applications with Silverlight.