Focus On Delivering Value to Your Patients.

Unit Tests for ViewModels AND Views in Silverlight

Contact Us Today

Over the past few posts I’ve been exploring models for modularized Silverlight applications that follow the MVVM pattern (using Prism/CAL). In this post, I’d like to cover unit testing, and writing appropriate tests not just for the view model, but the view itself.

Before we continue, I’m going to assume you’ve read:

These articles form the core of what I’m about to discuss. I also want to make sure you’re familiar with the Silverlight unit testing framework. You can download it and review some articles about how to use it over at the Unit Test Framework for Microsoft Silverlight page. I highly recommend pulling down the project and class templates as they will make your life easier!

The testing framework for Silverlight sets up a project that you run, and that project will then create a visual page that displays the results of tests. What’s important is that the test framework will not only support class tests, but can also host controls and test the hosted controls as well. Do we even want to do this? I think so.

Set up your test project and make it the runnable one by adding a new project to your existing Silverlight solution, using the Silverlight project template, then right-clicking on the project and setting it as the start-up project.

Let’s get started with a real example. I want to control the visibility of a control based on a boolean value in the view model, so I create a converter that takes in a boolean and returns visibility. I can bind the visibility like this:

<TextBlock Text="Conditional Text" Visibility="{Binding ConditionFlag,Converter={StaticResource BoolVisibilityConverter}}">

The code for the converter is simple:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}

To test that we get what we want, simply add a new class in your test project (use the Silverlight Test Class template). With a little bit of typing you will end up with something like this:

[TestClass]
public class BoolVisibilityConverterTest
{
    BoolVisibilityConverter _target;

    [TestInitialize]
    public void Initialize()
    {
        _target = new BoolVisibilityConverter();
    }

    [TestMethod]
    public void TestTrue()
    {
        object result = _target.Convert(true, typeof(bool), null, CultureInfo.CurrentCulture);
        Assert.IsNotNull(result, "Converter returned null.");
        Assert.AreEqual(Visibility.Visible, result, "Converter returned invalid result.");
    }

    [TestMethod]
    public void TestFalseNoParameter()
    {
        object result = _target.Convert(false, typeof(bool), null, CultureInfo.CurrentCulture);
        Assert.IsNotNull(result, "Converter returned null.");
        Assert.AreEqual(Visibility.Collapsed, result, "Converter returned invalid result.");
    }
}

Not rocket science there … but it’s nice to start out with a few green lights. When you run it, you’ll see that your two tests passed and all is well (you can, of course, assert something invalid to see what a failure looks like).

Now let’s test a view model. Our view model takes in a IService reference so that it can log a user in. It has bindings for username and password and a login command. The service looks like this:

public interface IService 
{
   void Login(string username, string password, Action<bool> result); 
}

So the view model looks like this:

public class ViewModel : INotifyPropertyChanged 
{
   private IService _service;

   public ViewModel(IService service)
    {
        _service = service;
       
        LoginCommand = new DelegateCommand<object>( o=>CommandLogin );            
    }  

    private bool _isDirty;

    public bool IsDirty
    {
        get { return _isDirty; }
    }

    private string _username, _password;

    public string Username
    {
        get { return _username; }
        set
        {
            if (value != null && !value.Equals(_username))
            {
                _username = value;
                OnPropertyChanged("UserName");                
            }
        }
    }

    public string Password
    {
        get { return _password; }
        set
        {
            if (value != null && !value.Equals(_password))
            {
                _password = value;
                OnPropertyChanged("Password");
            }
        }
    }

   public DelegateCommand<object> LoginCommand { get; set; }

   public void CommandLogin()
    {
        if (string.IsNullOrEmpty(_username))
        {
            throw new ValidationException("Username is required.");
        }

        if (string.IsNullOrEmpty(_password))
        {
            throw new ValidationException("Password is required.");
        }

        _service.Login(_username, _password, (result) =>
        {
            if (result)
            {
                // logic to navigate to a new page
            }
            else
            {
                throw new ValidationException("The username/password combination is invalid.");
            }
        });
    } 

    protected void OnPropertyChanged(string property)
    {            
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(property));
        }
        if (!_isDirty)
        {
            _isDirty = true;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs("IsDirty")); 
            }
        }
    }

    public void ResetDirtyFlag()
    {
        if (_isDirty)
        {
            _isDirty = false;
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs("IsDirty"));
            }
        }
    } 
}

Notice how properties being set should automatically set the “dirty” flag as well. I may want to bind my login button to the flag so it only becomes available when the user has changed something, for example. There is also a public method to reset the flag.

In order to satisfy my service, I’ll create a “mock” object. Why a mock, and not a stub? A stub is a piece of code you put in place to allow something to happen. If I wanted to stub my service, I’d do this:

public class ServiceStub : IService
{
   public void Login(string username, string password, Action<bool> result)
   {
      result(true); 
   }
}

This would always call back with a valid user and stubs out the functionality so I don’t have to implement a real login. A mock object, on the other hand, changes. To make this a mock, I do this:

public class ServiceMock : IService 
{
   public bool LoginCalled { get; set; }

   public void Login(string username, string password, Action<bool> result)
   {
      LoginCalled = true;
      result(true); 
   }
   
}

The class is a mock because it changes based on how it is used, and then we can query that change to see if our code is doing what we want. So let’s set up some tests with the view model:

[TestClass]
public class ViewModelTest
{

    private ViewModel _target;
    private ServiceMock _service;

    [TestInitialize] 
    public void Initialize()
    {
        _service = new ServiceMock();
        _target = new ViewModel(_service);

    }

    [TestMethod]
    public void TestConstructor()
    {
       Assert.IsFalse(_target.IsDirty,"Dirty flag should not be set."); 
       Assert.IsFalse(_service.LoginCalled,"Login should not have been called.");
       Assert.IsNotNull(_service.LoginCommand, "Login command was not set up."); 
    }
}

You can test that the username hasn’t been populated, for example. Now we can do a little more. In the example, we throw a ValidationException (a custom class) when the username is invalid. The Silverlight 3 validation framework can capture this based on data binding and show appropriate error messages to the client. We want to make sure if we try to login, we throw the exception, so we can do this:

[TestMethod]
[ExpectedException(typeof(ValidationException))]
public void TestLoginValidation()
{
   _target.CommandLogin(); 
}

Here we call the login command on the empty object and it should throw (and catch) the exception we’re looking for.

Finally, to use our mock object, we can set a valid user name and password and call the login command, then verify that the mock object was called:

[TestMethod]
public void TestLogin()
{
   _target.Username = "Valid Username"; 

   //bonus test: check that the dirty flag got set
   Assert.IsTrue(_target.IsDirty, "Dirty flag was not set on update."); 

   _target.Password = "Password"; 
   _target.CommandLogin();

   Assert.IsTrue(_service.LoginCalled); 
}

After testing your view model, you can then begin to work on testing the view itself. In the “required reading” I discussed having a generic view base that would interact with a navigation manager to swap views into and out of view. The views are all contained in an ItemsControl, and register to a view change event. If the view goes out of focus, it moves to a hidden state. If the view comes into focus, it moves to a visible state. While this allows more control over the way the states appear and how to transition between states, there is also the chance someone may add a view and forget wire in the visual state groups. The VisualStateManager won’t complain, but it can look ugly. We need to test for things like this!

Fortunately, the testing framework allows for us to host actual views. It provides a testing surface that we add controls to, and those controls are rendered so you can then inspect the visual tree. In this case, we want to emulate a view navigating to a new view and test that it is moved to the correct state.

Create a new test class. This time, however, we will inherit from the base class SilverlightTest which provides our class with a test panel to host controls on. The set up is a bit more involved, because we need to fold the mock services into the view model, then create the view and glue it all together.

Before we do this, we’ll create a helper class called QueryableVisualStateManager. This class is one I borrowed from Justin Angel’s fantastic blog post about Custom Visual State Managers. In his post, he details how to create a custom visual state manager that holds a dictionary of the control states so they can be queried later on (in case you’ve been pulling your hair out in frustration, the framework does not provide direct access to query the current visual state of controls).

I created the class verbatim, but don’t care to use it in production code. Instead, we’ll inject it in our test class. Here’s the setup:

[TestClass]
public class LoginTest : SilverlightTest
{
    private Login _login;
    private ViewModel _viewModel;
    private ServiceMock _service;
    private NavigationManager _navigationManager;
    private QueryableVisualStateManager _customStateManager; 

    [TestInitialize]
    public void TestInitialize()
    {
        _login = new Login();
        
        FrameworkElement root = VisualTreeHelper.GetChild(_login, 0) as FrameworkElement;
        root.SetValue(VisualStateManager.CustomVisualStateManagerProperty, new QueryableVisualStateManager()); 

        _service = new ServiceMock();
        _navigationManager = new NavigationManager();
        _viewModel = new ViewModel(_service);
        _viewModel.Navigation = _navigationManager;
        _login.DataContext = _viewModel;
        TestPanel.Children.Add(_login);
    }
}

What happened? Login is my user control … it is the view I inject into the shell to show the login page. Here I create an instance of it. Then, I use my friend the VisualTreeHelper to parse the the first child, which is going to be the grid or stack panel or whatever “host” control you have inside your user control. Then, I simply set the attached property for the custom view manager to point to the queryable helper class. This will ensure any visual state transitions are recorded in the internal dictionary. Then I wire up my mocks, databind, and finally add the login control to the TestPanel. It now gets hosted on a real test surface and can initialize and display.

Let’s assume that the navigation manager I injected is responsible for swapping the view state of the control. The control goes into a HideState when not visible and a ShowState when visible. What I want to test is a simulated login command. We already tested this in the view model, so we can be confident it is going to hit the service and do what it is supposed to do. There is a piece of code that then calls the navigation manager and changes the control’s state to hidden. We want to test that this hook actually gets fired when the user clicks login, so the login view disappears. Here’s how:

[TestMethod]
public void TestLogin()
{
    const string SHOWSTATE = "VisualStates.ShowState";
    const string HIDESTATE = "VisualStates.HideState";

    // set up this view
    _navigationManager.NavigateToPage(NavigationManager.NavigationPage.Login);
                
    string state = QueryableVisualStateManager.QueryState(_login);
    Assert.IsTrue(state.Contains(SHOWSTATE) && !state.Contains(HIDESTATE), "Invalid visual state."); 

    // trigger login 
    _viewModel.Username = "user";
    _viewModel.Password = "password";
    _viewModel.CommandLogin();
   
    state = QueryableVisualStateManager.QueryState(_login);
    Assert.IsTrue(state.Contains(HIDESTATE) && !state.Contains(SHOWSTATE), "Invalid visual state."); 
}

We first test the pre-condition by navigating to the login page and confirming it has the ShowState and not the HideState. Then, we simulate a login action (this is why command binding and view models are so powerful) and query the state again, testing to make sure we went into a hidden state.

When you run this test, you might actually see the control flicker for a moment on the screen as it gets initialized on the test surface before it is manipulated and then discarded for other tests. With the right architecture, you are now able to test from the view down to the backend services that drive your application. Now that’s powerful!

Jeremy Likness

Take advantage of our free assessment and Azure credits.

We understand that evolving your IT can be costly.
We are offering you a unique opportunity to save you money and get you started faster.

Get $2,500 Azure Credits and a Free Architecture Roadmap

Assess and Migrate Your Existing Environment

Improve Your Information Security and Compliance

Get up to 5 hours of architecture work and $2,500 worth of Azure credits, free of charge.

We right-size your systems and move them into an optimized environment.

We work closely with your team to develop the right roadmap.

Atmosera cited by Gartner as a Representative Vendor in the Market Guide for Cloud Service Providers to Healthcare Delivery Organizations

Read Press Release

We help healthcare solution providers make the most of the cloud.

We are a Gold certified Microsoft Azure service provider offering a comprehensive set of managed services.
We excel at working with care providers and their ecosystem of solution providers.

Collaborate with Experts

Migrate Environments

Maintain Confidence

We take on your infrastructure concerns as an extension of your team and tackle compliance including HIPAA/HITECH and HITRUST.

Our methodology encompasses design through deployment and focuses on delivering solutions which are realistically implementable.

Rely on our deep knowledge of critical security frameworks and 24x7x365 monitoring by a team of experts.

We Know Healthcare:

We are fortunate to count a number of leading care providers and healthcare vendors as our customers. We continue to grow this segment as companies turn to secure and compliant cloud solutions.

Our Customers Include:

All Care Services, CarePayment Technologies, Consonus Healthcare, Digital Visions, Fanno Creek Clinic, First Insight, Health Share of Oregon, Marquis Companies, MediPro Direct, Metropolitan Pediatrics, Navos, OCHIN, Oregon State Hospital, Planned Parenthood, ProtoCall Services, Salem Health, Seasons Management, The Portland Clinic, Touchmark, Vistalogic, WVP Health Authority.

View Data Sheet View Case Study

Collaborate with Experts

  • Plan out your cloud strategy without having to commit all your applications to the public cloud
  • Microsoft has the only viable hybrid strategy and expected to surpass AWS in market share by 2019.
  • We specialize in engineering, deploying and operating the right solution for your business by combining public and private Azure.
  • As one of the world’s five largest Microsoft cloud solution providers (CSP), we help you identify the optimal environment to run each application including your database and storage.
  • Meet HIPAA/HITECH, HITRUST and PCI DSS compliance

Migrate Environments

  • We have expertise which minimizes redevelopment to move applications and data without recoding.
  • We leverage Microsoft Azure Site Recovery (ASR) which provides a simple way to move applications and data without having to redevelop the underlying cloud infrastructure.
  • We implement your new environment on a public or private cloud depending on your preferences and business requirements.
  • We enable access to complete and accurate PHI for better medical care.

Maintain Confidence

  • Ensure you are secure from design through deployment.
  • Eliminate concerns about exposing your PHI and Non-PHI data when using the public cloud.
  • Define your objectives and build the right foundation using best practices and then execute it.
  • You gain the peace of mind that comes from knowing we have planned out your cloud to the smallest details and then made sure it delivers on your needs.
  • Let our team monitor your environment and take real-time actions to keep your applications running at their best.

We deliver solutions that accelerate the value of Azure.

Ready to experience the full power of Microsoft Azure?

Start Today

Blog Home

Stay Connected

Upcoming Events

All Events