Home > Articles > Web Development > ASP.NET

Silverlight Best Practices: Testing Soup to Nuts

  • Print
  • + Share This
In this last installment of the series covering best practices for Silverlight in the enterprise, Microsoft MVP for Silverlight Jeremy Likness discusses testing. Read this article to learn about various approaches to testing Silverlight applications from “white box” unit tests to coded UI tests.
Like this article? We recommend

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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020