Unit Testable Code with MVVM

Published: Fri Jun 12 2015

Writing unit tests for UI code can be tricky. The code is usually full of dependencies on user interactions that present challenges when attempting to write unit tests.

In this article I will describe how to reduce the impact of these dependencies by using the unit test friendly pattern Model-View-View-Model (MVVM).

Model-View-View-Model

As with all other Model-View-X patterns, the key idea behind MVVM is to design testable code with a clear separation between view code and application code. This separation is very difficult to achieve in the classic “code-behind” design that you often see in UI projects today, but with MVVM this becomes a lot easier.

This article will describe, through a simple sample project, how view models can be used to create fully testable UI code.

The example used in the article is a simple WPF temperature converter for converting between Fahrenheit and Celsius. WPF is extremely well suited for MVVM, but the pattern is in principle applicable to other UI technologies as well.

The most important component is the TemperatureConverterViewModel (Code listing 1) class which encapsulates all the application code for the converter. The idea is that no logic will exist outside of the view model, and the interface between the view and the view model is data binding. TemperatureConverterViewModel binds to the UI using change aware properties that are coded to detect changes resulting from either user action or code assignments.

The WPF binding model is very powerful and extremely flexible, and as a result there is no need for boilerplate code in the code-behind to manage assignments and updates of UI controls. Instead it's all defined in the xaml (Code listing 2). As you can tell, there is only a single line of code in the code-behind (Code listing 3).