Tag Archives: Unit Testing

String localization for XAML and C# using dynamically implemented interface

In this post I will describe a solution for easy localized strings management in XAML or C#. Precisely, we will use the usual recommended material for manipulating localized strings in .NET: resx files and the ResourceManager class. However, for XAML manipulation, we will add a “type layer” on top of this. We will see that having typed resources can be very useful. The “type layer” is basically an interface where string properties contain the localized strings, then in XAML or C# code the translations are accessed by using directly these properties. To avoid painful repetitions, the implementation of the interface is dynamically generated using some very simple MSIL. To conclude, we will write simple unit tests that check that the translation files (.resx) contains all the localized strings for all supported languages.

First, let us recall that it is really important that your localized strings are not dispersed in the source code of your application. Using a code snippet of the following form is a bad practice.

//don't do this
TextBox.Text = LocalizeUtil.Localize("Hello","Bonjour","Bon dia");

Indeed, it is very important that you keep grouped all the translations for a given language in one file. Then, you could rework your translations on your own or with a professional without having to grep the entire code base.

Fortunately, .NET comes with all the material you need to handle Culture-Specific resources with the ResourceManager. Say you support english (default) and french languages then you have two .resx files which contains key/value string entries. Such files are named LocalizedStrings.resx and LocalizedStrings.fr-FR.resx they may contain, among others, the entry SayHello (“Hello!” in english and “Bonjour !” in french). Finally, you only have to initialize the ResourceManager and getting the localized strings as follows.

var rem = new ResourceManager("LocalizedStrings", Assembly.GetExecutingAssembly());
Console.WriteLine(rem.GetString("SayHello"));

It is important to note that the right file (*.resx or *.fr-FR.resx) is automatically chosen using the Tread.CurrentThread.CurrentUICulture.

When manipulating XAML for the UI of your app, creating a type for the localized string is recommended. Indeed, in XAML you can bind to properties but you cannot (at least not easily) bind to methods. So the recommended method from the MSDN is to create a LocalizedStrings class whose members are the localized strings.

So we can create the LocalizedStrings class

public class LocalizedStrings
{
    private readonly ResourceManager _rem
    public LocalizedStrings(ResourceManager rem)
    {
        _rem = rem;
    }

    public string SayHello
    {
       { get {return _rem.GetString("SayHello"); }
    }

    public string SayHelloAgain
    {
       { get {return _rem.GetString("SayHelloAgain"); }
    }

    /* A lot of properties more..... */
}

While the instance is retrieved using a Singleton-like pattern (there is no reason to mock this for testing so it makes sense to use a singleton here).

public class StringLocalizer
{
    private static LocalizedStrings _localizedStrings;

    public static LocalizedStrings Strings
    {
        get
        {
            if (_localizedStrings == null)
            {
                  _localizedStrings = new LocalizedStrings(new ResourceManager("LocalizedStrings", Assembly.GetExecutingAssembly())));
             }
             return _localizedStrings;
        }
     }
}

We can use easily the LocalizedStrings in the xaml after adding the StringLocalizer has an application resource.

<!-- set the localizer has a resource -->
 <Application.Resources>
   <local:StringLocalizer xmlns:local ="clr-namespace:appNamespace"
                           x:Key="Localizer" />
 </Application.Resources>
 <!-- in the window or user control -->
 <Button DockPanel.Dock="Left"
         Command="{Binding Next}"
         ToolTip="{Binding Strings.SayHello, Source={StaticResource Localizer}}">

Obviously we can use the same class in the plain old C#

Console.WriteLine(StringLocalizer.Strings.SayHello);

Using this “type layer” is not only mandatory for XAML it is also very useful because we benefit from the static typing. Indeed, typing help us to create localized strings list that do not contain tons on unused entries. Even if this is not a matter of life or death, it is a good thing to remove unused localized strings from your dictionaries, because they going to cost you some effort or money when you will make new languages available or if you want to review the terminology used in your application. The only thing you have to do is to search for unused member of the class (the plugin Resharper does this well even in XAML).

As shown in the image below the XAML-intellisense of Resharper shows us all members of the interface which is handy to reuse localized strings.

The plugins resharper shows all properties of the LocalizedStrings class

The plugins resharper shows all properties of the LocalizedStrings class

Still there is one thing which is cumbersome, every-time you create a new entry you have to type the same logic for the property: _rem.GetString(“NameOfTheProperty”). Then, it’s time to be nerdy and find a way to do this automatically! Let us replace the LocalizedStrings class by and interface ILocalizedStrings whose implementation is dynamically generated. You can emit dynamically new type in .NET using the ILGenerator. So this is the implementation of the new StringLocalizer with some help from the .NET IL guru Olivier Guimbal.

So here it is what the interface looks like

public interface ILocalizedStrings
{
    void SetResMan(ResourceManager man);

    string SayHello{ get; }
    string SayHelloAgain{ get; }
    /* A lot of properties more..... */
}

And here is the StringLocalizer

public class StringLocalizer
{
    private static class InstanceGenerator
    {
        static readonly Dictionary<Type, ILocalizedStrings> Implementations = new Dictionary<Type, ILocalizedStrings>();
        static int _implCount = 0;

        static ModuleBuilder _moduleBuilder;
        static ModuleBuilder ModuleBuilder
        {
            get
            {
                if (_moduleBuilder != null)
                    return _moduleBuilder;
                var assemblyName = new AssemblyName { Name = "Services" };
                AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
                _moduleBuilder = assemblyBuilder.DefineDynamicModule("ServicesModule", "ServicesModule.dll");
                return _moduleBuilder;
            }
        }

        public static ILocalizedStrings CreateImplementation()
        {
            Type interfaceType = typeof(ILocalizedStrings);
            if (!interfaceType.IsInterface)
                throw new ArgumentException(interfaceType + " is not an interface type");

            ILocalizedStrings found;
            if (Implementations.TryGetValue(interfaceType, out found))
                return found;

            var module = ModuleBuilder;
            var tb = module.DefineType(interfaceType.FullName + "Impl" + (_implCount++), TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(object), new[] { interfaceType });

            FieldBuilder fld = tb.DefineField("_resourceManager", typeof(ResourceManager), FieldAttributes.Private);

            var setter = tb.DefineMethod("SetResMan", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, typeof(void), new Type[] { typeof(ResourceManager) });
            MethodInfo setMethodInfo = typeof(ILocalizedStrings).GetMethod("SetResMan");

            var setterIl = setter.GetILGenerator();
            setterIl.Emit(OpCodes.Ldarg_0);
            setterIl.Emit(OpCodes.Ldarg_1);
            setterIl.Emit(OpCodes.Stfld, fld);
            setterIl.Emit(OpCodes.Ret);

            tb.DefineMethodOverride(setter, setMethodInfo);

            var props = interfaceType.GetProperties();

            foreach (var pi in props)
            {
                if (pi.PropertyType != typeof(string))
                    throw new ArgumentException("Only string properties are supported");

                if (pi.CanWrite)
                    throw new ArgumentException("Property must be read-only: " + interfaceType + " -> " + pi.Name);

                MethodInfo methodInfo = pi.GetGetMethod();
                var mb = CreateOverride(tb, methodInfo);

                var il = mb.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, fld);
                il.Emit(OpCodes.Ldstr, pi.Name);
                il.Emit(OpCodes.Call, typeof(ResourceManager).GetMethod("GetString", new[] { typeof(string) }));
                il.Emit(OpCodes.Ret);

                PropertyBuilder pb = tb.DefineProperty(pi.Name,
                       PropertyAttributes.HasDefault,
                        CallingConventions.HasThis, methodInfo.ReturnType,
                        methodInfo.GetParameters().Select(p => p.ParameterType).ToArray());
                pb.SetGetMethod(mb);
            }

            found = (ILocalizedStrings)Activator.CreateInstance(tb.CreateType());
            Implementations.Add(interfaceType, found);
            return found;
        }

        static MethodBuilder CreateOverride(TypeBuilder tb, MethodInfo mi)
        {
            var mb = tb.DefineMethod(mi.Name,
                        MethodAttributes.Public
                        | MethodAttributes.HideBySig
                        | MethodAttributes.NewSlot
                        | MethodAttributes.Virtual
                        | MethodAttributes.Final,
                        CallingConventions.HasThis, mi.ReturnType, mi.GetParameters().Select(p => p.ParameterType).ToArray());
            tb.DefineMethodOverride(mb, mi);

            return mb;
        }
    }

    private static ILocalizedStrings _localizedStrings;

    public static ILocalizedStrings Strings
    {
        get
        {
            if (_localizedStrings == null)
            {
                _localizedStrings = (ILocalizedStrings)InstanceGenerator.CreateImplementation();
                _localizedStrings.SetResMan(new ResourceManager("LocalizedStrings", Assembly.GetExecutingAssembly())));
            }
         return _localizedStrings;
        }
    }
}
Tests are failing because some properties of the ILocalizedStrings are missing in the resx.

Tests are failing because there are some unused entries in the resx.

To conclude let us write unit tests to ensure that all properties in the interface ILocalizedStrings are defined on all .resx files and, reciprocally, to make sure that all keys in the resx files are properties of the interface. This will help us to track non translated entries and to remove useless keys in the resx dictionaries. We basically parse the .resx files to retrieve all keys and use reflexion to get all public properties of the interface. The test fail when problematic entries are discovered and printed in the test console.

[TestClass]
public class TranslationTests
{

   private TestContext _testContextInstance;
   public TestContext TestContext
   {
       get
       {
           return _testContextInstance;
       }
       set
       {
           _testContextInstance = value;
       }
   }

   private void TestPropertiesAndResxKeyAreEqual(string filePath)
   {
       XDocument xDoc = XDocument.Load(filePath);

       HashSet<string> resxKeys = new HashSet<string>(xDoc.Descendants("data").Select(c => c.Attribute("name").Value));
       HashSet<string> interfaceProp =
           new HashSet<string>(
               typeof (ILocalizedStrings).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                   .Select(p => p.Name));

       bool fail = false;
       foreach (var r in resxKeys)
       {
           if (!interfaceProp.Contains(r))
           {
               _testContextInstance.WriteLine(string.Format("The key {0} exists in resx but not in interface", r));
               fail = true;

           }
       }

       foreach (var property in interfaceProp)
       {
           if (!resxKeys.Contains(property))
           {
               _testContextInstance.WriteLine(string.Format("The key {0} exists in interface but not in resx", property));
               fail = true;
           }
       }
       if (fail)
       {
           Assert.Fail();
       }

   }

   [TestMethod]
   public void TestEnglishResx()
   {
       const string path = @"../../../MyApp/LocalizedStrings.resx";
       TestPropertiesAndResxKeyAreEqual(path);
   }

   [TestMethod]
   public void TestFrenchResx()
   {
       const string path = @"../../../MyApp/LocalizedStrings.fr-FR.resx";
       TestPropertiesAndResxKeyAreEqual(path);
   }
}

A generic version of ICollectionView used in a MVVM searchable list

In this post we will describe how to create a searchable list with WPF following MVVM principles. To this aim we will use a WPF ListView to display the searched items and a TextBox to enter the text used for the search. Most of the implementation that you will find on the web (e.g. this one) will recommend you to bind your ListView to an ICollectionView. However, this is not 100% satisfactory as long as ICollectionView does not have a built-in generic version. Consequently the ViewModel’s member exposing the binding items will return an ICollectionView which is a powerful object (see this for instance)  but is “only” an enumeration of System.Object. In this post we will show you that a generic version can be easily implemented and exposed by your ViewModel.

In this post we will create a very simple app that let you search a player in the list of all the players of the last Football World Cup in Brazil. The complete source code can be found on my Github here.

Searchable WPF ListView

Searching ‘dav’ in the ListView display a list of results starting with ex Chelsea’s player David Luis…

The key ingredients of such implementation is very simple in MVVM. First take the View which does not need more than the few lines of xaml below.

 <UserControl.DataContext>
 <Binding Path="PlayerSearchViewModel" Source="{StaticResource Locator}" />
</UserControl.DataContext>
<DockPanel>
 <TextBlock DockPanel.Dock="Top" Text="Search player"></TextBlock>
 <TextBox DockPanel.Dock="Top" Text="{Binding SearchPlayerText, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<ListView ItemsSource="{Binding DisplayedPlayers}" SelectionMode="Single" ScrollViewer.VerticalScrollBarVisibility="Auto">
  <ListView.View>
   <GridView >
    <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" />
    <GridViewColumn DisplayMemberBinding="{Binding NationalTeam}" Header="National Team" />
    <GridViewColumn DisplayMemberBinding="{Binding Age}" Header="Age" />
    <GridViewColumn DisplayMemberBinding="{Binding Club}" Header="Club"/>
    <GridViewColumn DisplayMemberBinding="{Binding Championship}" Header="Championship"/>
   </GridView>
  </ListView.View>
 </ListView>
</DockPanel>

Let us start by exposing the non-generic version: the DataContext of the control above is bound to an instance of an implementation of the interface IPlayerSearchViewModel below.

public interface IPlayerSearchViewModel
{
   string SearchPlayerText { get; set; }

   ICollectionView DisplayedPlayers { get; }
}

A very straightforward implementation that works is the following one.

public class PlayerSearchViewModel : IPlayerSearchViewModel
{
    private readonly ICollectionView _view;
    private string _textsearch;

    public PlayerSearchViewModel(IPlayerProvider playerProvider)
    {
        _view = CollectionViewSource.GetDefaultView(playerProvider.GetAllWorldCupPlayer());
        _view.Filter += (object item) =>
        {
                    if (_textsearch == null) return true;
                    var itemPl = (IPlayer) item;
                    return itemPl.Name.Contains(_textsearch) ||
                               itemPl.NationalTeam.Contains(_textsearch) ||
                               itemPl.Club.Contains(_textsearch) ||
                               itemPl.Championship.Contains(_textsearch);
        };
    }

    public string SearchPlayerText
    {
        get { return _textsearch; }
        set
        {
            _textsearch = value;
            _view.Refresh();
        }
    }

    public ICollectionView DisplayedPlayers { get { return _view; } }
}

As I said in the introduction, this is quite enoying. You may want to create screens with many ICollectionView bindings that may contain different types, then it is becoming error prone and we are loosing the benefit of C#’s type safety. The unit test example below is showing you that the elements need to be casted while they are accessed from the ICollectionView.

[TestMethod]
public void TestingTheSearchingCapabilitiesWithBedoya()
{
    var viewModel = new PlayerSearchViewModel(new PlayerProvider());
    viewModel.SearchPlayerText = "Bedoya";
    var searchResult = viewModel.DisplayedPlayers.Cast<IPlayer>().ToArray(); //Cast objects extracted from the ICollectionView
    Assert.AreEqual(1, searchResult.Length);
    IPlayer bedoya = searchResult[0];
    Assert.AreEqual("Nantes",bedoya.Club);
}

In addition we cannot use anymore the XAML validation and intellisense provided by Resharper.

Resharper complaining because of the unknown's member of the DataContext (typed as object)

Resharper complaining because of the unknown’s member of the DataContext (typed as object)

Fortunately we can create our generic version of ICollectionView and get back to the comfortable world of type safety. In this example, I will only provide the generic enumeration and the generic version for the SourceCollection member but you can add others. Indeed, you may create a generic version of the Filter predicate to avoid dealing with System.Object in your lambdas but with your generic type T instead.

public interface ICollectionView<T> : IEnumerable<T>, ICollectionView
{
    IEnumerable<T> SourceCollectionGeneric { get; }
    //Add here your "generic methods" e.g.
    //e.g. Predicate<T> Filter {get;set;} etc.
}

Actually, the implementation of the ICollectionView is really easy as long as you already have the non-generic instance at hand ICollectionView

public class MyCollectionViewGeneric<T> : ICollectionView<T>
{
    private readonly ICollectionView _collectionView;

    public MyCollectionViewGeneric(ICollectionView generic)
    {
        _collectionView = generic;
    }

    private class MyEnumerator : IEnumerator<T>
    {
        private readonly IEnumerator _enumerator;
        public MyEnumerator(IEnumerator enumerator)
        {
            _enumerator = enumerator;
        }

        public void Dispose()
        {
        }

        public bool MoveNext()
        {
            return _enumerator.MoveNext();
        }

        public void Reset()
        {
            _enumerator.Reset();
        }

        public T Current { get { return (T) _enumerator.Current; } }

        object IEnumerator.Current
        {
            get { return Current; }
        }
    }

    public IEnumerator<T> GetEnumerator()
        {
            return new MyEnumerator(_collectionView.GetEnumerator());
        }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _collectionView.GetEnumerator();
    }

    public bool Contains(object item)
    {
     return _collectionView.Contains(item);
    }

    public void Refresh()
    {
        _collectionView.Refresh();
    }

       //Complete implementation can be found on github.co/bpatra/MVVMSample

    public event NotifyCollectionChangedEventHandler CollectionChanged
    {
        add
        {
            lock (objectLock)
            {
                _collectionView.CollectionChanged += value;
            }
        }
        remove
        {
            lock (objectLock)
            {
                _collectionView.CollectionChanged -= value;
            }
        }
    }

    public IEnumerable<T> SourceCollectionGeneric

        get { return _collectionView.Cast<T>(); }
    }
}

Therefore the implementation of the the ViewModel becomes cleaner and statically typed. First the new version of the ViewModel interface.

public interface IPlayerSearchViewModel
{
    string SearchPlayerText { get; set; }

    ICollectionView<IPlayer> DisplayedPlayers { get; }
}

Then, the implementation.

public class PlayerSearchViewModel : IPlayerSearchViewModel
{
    private readonly ICollectionView<IPlayer>; _view;
    private string _textsearch;

    public PlayerSearchViewModel(IPlayerProvider playerProvider)
    {
        _view = new MyCollectionViewGeneric<IPlayer>;(CollectionViewSource.GetDefaultView(playerProvider.GetAllWorldCupPlayer()));
        _view.Filter += (object item) =>;
        {
            if (_textsearch == null) return true;
            var itemPl = (IPlayer) item;
            return itemPl.Name.Contains(_textsearch) ||
                        itemPl.NationalTeam.Contains(_textsearch) ||
                        itemPl.Club.Contains(_textsearch) ||
                        itemPl.Championship.Contains(_textsearch);
        };
    }

    public string SearchPlayerText
    {
    get { return _textsearch; }
        set
        {
            _textsearch = value;
            _view.Refresh();
        }
    }

    public ICollectionView<IPlayer>; DisplayedPlayers { get { return _view; } }
}

You do not have to cast or worry anymore on the the type of the objects contained in you ICollectionView. You will also detect binding errors statically with Resharper.

resharperClever

Resharper handles typed generic collections in databinding

Tools for javascript TDD with Visual Studio

In this post I describe the tools that I have selected for efficient development of javascript tests within Visual Studio. Indeed, if you are developing sites with ASP.NET or Apps for Office then you are more or less committed to use Visual Studio. Therefore, you probably do not want to use another editor for the javascript development.

What were my requirements when I chose the tools that I will describe to you in this post? Actually, I needed tools which can provide me the same comfort that I have while I am developing in TDD with .NET. Precisely, the test should be run individually (or at least individually for a given set). They should be run on the continuous integration build, which is teamcity in my case. The test runner may use any browser for executing the tests even if flexibility for using all kind of browsers would be appreciated. In addition, the test should be easily debugged and this is a very important aspect for me.

Let me detail a little this latter requirement. Indeed, I have read recently this blog post and its written that

Debugging the tests
Wiseman said: “If you need to debug unit test then something is wrong with it’s unitness.”
PS: If it’s really needed you can debug it in browser as you normally debug JavaScript code.

Even if the rest of the blog is brilliant, I do not agree at all with this sentence.  If you practice regularly TDD then you’ll see that you have to debug, that’s part of the game. If you never have to debug maybe it’s because you are asserting too much trivialities and not enough your own complex logic. In addition, if you have to create the webpage on your own, for debugging, that is not acceptable to me either. You should be able to put your breakpoint anywhere in your code and hit it in less than five seconds. We will see that the tool chosen permits such quick debugging and that’s the main reason why I am using it.

At the time of the writing, the popular Visual Studio Addin Resharper with its version 8 supports javascript tests with the frameworks Jasmine or QUnit. Unfortunately, the debugger cannot be properly attached while debugging the scripts. Sadly, I had to reject Resharper that I appreciate so much for .NET development.

Finally, the best tool that I found is Chutzpah (which means Audacity in Yeddish). Firstly, there is the Chutzpah runner which is a javascript test runner that uses the headless browser phantomJs, we will invoke it from the command line in the continuous build. Sedondly, there is the Chutzpah Visual Studio extension which enables quick runs and debugging sessions from Visual Studio. Both runner and Visual Studio extension is fully compatible with JS test framework Jasmine 2.0. that I have chosen. Note that I also use the mocking library sinonJs but I won’t discuss it there.

You may retrieve the code samples below on my github repository.

To illustrate these tools we will use a very simple mockup project and we start its description with the following VisualStudio solution.

The Visual Studio solution describing the example of this post.

The Visual Studio solution describing the example of this post.

As usual there are two projects: WebApplication1, the core project, containing the app folder with our javascript logic, especially the one that we would like to test: sut.js (for SystemUnderTest). There is also the test project, WebApplication1.Tests. The file testing the logic contained in sut.js is simply sutTests.js. The testing framework Jasmine is added to the solution by referencing the folder lib/jasmine-2.0.0..

We will take a very simple example, where the object app.sut has a function for computing the factorial of an integer. The code of sut.js can be found in the following snippet.

(Note that in app we have implemented a basic namespacing function such as this one)

Let us now focus on the test suite in the sutTests.js code.

This piece of code is very basic Jasmine syntax for a test suite. We assert the values of the factorial function for the two corner cases where the input is 0 and 1 and we also test the situation with n=5. Remark also that we have a test which asserts that an exception is thrown when a non positive value is passed to the function. We have not covered this situation with the snippet above, consequently, we expect this test to fail… Remark that all the needed references to js files are handled with ///<reference of Visual Studio. By the way, we benefit from Visual Studio Intellisense here.

The Javascript intellisense with Visual Studio

The javascript Intellisense with Visual Studio

In the next screen shot, we run the tests with the Visual Studio Test Explorer that is compatible with Jasmine thanks to Chutzpah.

Run all our test with the Visual Studio Test Explorer. As expected we encounter a failure.

Run all our test with the Visual Studio test explorer. As expected we encounter a failure.

If we were in the situation where we do not know what is going wrong (which is often the case) we would need to debug the test. Unfortunately, like Resharper, you cannot debug the test directly in VisualStudio, the debugger does not attach well. Even Chutzpah creator does not know how we would do that, so I believe we will have to wait to debug javascript test as easily as we debug .NET within visual studio. Then, we will have to debug with a web browser. However, Chutzpah creates the webpage for bootstrapping your failing test. So just by clicking in Open in browser you will have the web page loaded and a link to run the failing test within the browser (see screenshots below).

Chutzpah Visual Studio extension creates web page for running/debugging tests in the web browser.

Chutzpah Visual Studio extension creates web page for running/debugging tests in the web browser.

Then the debugging sessions happens in your browser. Reclicking the links reexecutes the tests.

Then the debugging sessions happens in your browser (here Chrome). Clicking again the links reexecute the tests.

Now, we do have all the material for editing efficiently tests in Visual Studio. Let us have a few words for running the test using the command line on the server. Personally, I embed the Chutzaph runner in a /build directory within my sources and executes the following Powershell script.

Here is what it looks when ran it an Powershell console with teamcity options.

The execution of all javascript tests of the solution with Chutzpah runner using Powershell

The execution of all javascript tests of the solution with Chutzpah runner using Powershell

To conclude, I would say that Chutzpah is a great project and if you need a simple and ready to use test runner I would recommend it. The only limitation for now  would be that the runner only supports phantomJS. However, you may use another another test runner for executing the tests with different browser and you can keep the Chutzpah Visual Studio extension for the development. One last important thing to note is the fact that Chutzpah 3.0 supports RequireJs.

Unit Testing Drag and Drop logic with MVVM pattern in WPF

I recently had a discussion with a friend about the Model-View-ViewModel pattern (MVVM) for UI apps and the fact that it allows unit testing where you would not have thought it possible in the first place, for example, logic involved by drag and drop. We agreed on the fact that most of MVVM posts are very theoretical regarding MVVM and when they are not, the testing part, is only mentioned never detailed. That is why I decided to write this concrete post focusing as much as possible on the testing topic.

 

The objective of this post is to detail the code architecture and the techniques involved to the testing of a very simple WPF app. This app enables the user to rank via drag and drop the list of the french football clubs and save this ranking. This could be a part of larger app that could be used, for example, to bet the final table… However for the sake of simplicity of this post we will focus mainly on the WPF control ListView containing the football club rows. The source code can be found in this github repository.

 

List view control displaying the football clubs that can be reorganized by drag and drop. The order can be saved

List view control displaying the football clubs that can be reorganized by drag and drop. The order can be saved.

We will use an external library that wraps all the complex events handling regarding the mouse action involved in the drag and drop. Following unit testing principles, we will only test our logic which will be the movement of elements in the collection the ListView is bound to. In order to add little bit of extra complexity, we would like to allow not only the movement of one row but also of a block of contiguous rows.

 

There are tons of blog posts and articles on theoretical description of MVVM written by brilliant developers so I will try to be as brief as possible and will focus more on the example.  The fundamental and natural principle on which MVVM and other UI pattern are based on is to separate the UI from the business logic. In one sentence, the application logic should not be tied to UI elements. The Model/View/ViewModel comes in three parts as well summarized in this blog
  • A view is simply a UI page. It does not know where the data is coming from.
  • A ViewModel holds a certain shape of data, and commands, that a View binds to.
  • The model refers to the actual business data, which is used to populate the ViewModels.
The basic interaction rules can be summarized in the drawing below.
MVVM interactions overview

MVVM interactions overview

Speaking more in term of WPF, the view contains the UserControls, the windows. A view class definition is split between the xaml file (simplifying UI design) and the associate .cs file called code behind. If an application is coded following MVVM principles the code behind should be small, containing code on the UI elements that are difficult to expressed with XAML syntax (e.g. keyboard bindings).

 

Now it is time, to present the external tools that we are going to use in this small app. The drag and drop mouse interaction will be handled by the open source project GongWPF. For unit testing we will use the Visual Studio Test framework and Moq for creating mock objects. For a real and more sophisticated app written with MVVM, I would recommend you to use a framework. Personally, I do like MVVMLight.

 

Let us describe the code of our app starting by the so-called model part. This is a natural way because, in real scenarios this may be existing parts, written before ever considering the UI. However, in this fake app it is going to be very simple. The main business interface is IFootballClub exposing three properties regarding the club.
The core model is represented by the interface IChampionship. It is extremely lightweight in our situation because, in this post, we want to focus more on the View/ViewModel interaction. However, we have added the property CurrentChampionShipRanking and GetGoodBetCount as examples of methods that could be put in the model.
Let us now present the interface for our ViewModel, IChampionshipViewModel, which is the most important part of this blog post. Therefore, it will be the only interface where we provide the implementation. This implementation will handle the drag and drop core logic and will be the system under test for our matter. The list of football clubs will be kept in the FootballClubs observable collection. This collection handles natively all the notifications for the view. The Save action will be handled by the SaveClick property whose type is ICommand. An ICommand is an interface for an action that can be executed.

 

Remark also that IChampionshipViewModel extends IDropTarget which is the main interface provided by GongWPF for handling the drag and drop events. This interface contains two methods void DragOver(IDropInfo dropInfo) and void Drop(IDropInfo dropInfo)
To complete the overview let us present the xaml for our view. Indeed, following MVVM principles, our custom UserControl is essentially XAML leaving no code behind. The most important part is the binding of the View to the ViewModel via the DataContext property. In our case, we have used a ViewModelLocator (a very simple one with no IoC container) see  this post for more information on the ViewModelLocator pattern. Naturally, the ListView ItemsSource (the list of rows) is bound to the FootballClubs property of the IChampionshipViewModel interface. For each column, we can bind to a property of the interface IFootballClub. Note also, that the Resharper AddIn enables intellisense and type validation of those bindings which is really valuable for early detection of errors.
Finally, the ListView control has the following GongWPF attributes:
dd:DragDrop.IsDragSource=”True”, dd:DragDrop.IsDropTarget=”True”, dd:DragDrop.DropHandler=”{Binding}”

Thanks to these attributes, GongWPF will be able to make a bridge between the mouse UI events and the methods of the IDropTarget interface which our ViewModel extends.

Unfortunately, as brilliant as it is, GongWPF does not do everything and its our responsibility  to implement the logic that moves the elements within the ObservableCollection FootballClubs. 
Following the TDD principles let us write tests first. But before that, let us have a glimpse at our SUT (system under test) which is the class ChampionshipBetViewModel. The model IChampionship is injected as a constructor parameter. We will not discuss further the SaveClick part but we use a custom implementation of the ICommand interface which basically execute the lambda expression passed as parameter. This Action typed lambda updates our model with the reranked list of football clubs.
Here comes our first unit test. I think it is a good thing when a test can expressed in term of a simple sentence such as “Given… When … Then…”. Logically, the test method name should be closed to this sentence. The first one will assert that ” given a list of four rows when the the source is the first row and the target is the second one then the list of row should be reordered“. Remark that the target (the InsertIndex in GongWPF API) corresponds to the row instance preceding the inserted item. Being clear with this convention, the GongWPF interfaces are easily mocked using Moq, resulting in the following unit test. We assert that after executing the Drop method the list is club2, club1, club3, club4

For having a proper case coverage it is also important to assert “negative” situations such as the following one “given a list of four rows, if the source is the block containing the two last rows and the target is the second one then the drop action should not change the order

Remind, that we have for specification to be able to move a block of contiguous rows at once but we do not want to move two discontinuous blocks. Therefore, the DragOver method should handle properly this situation: the styling that allows insertion should be set in the first situation and not set at all in the second one. To assert this with unit tests, we use the VerifySet methods on the mock object dropInfo. For both properties DropTargetAdorner and Effects, we verify they are set when the selected items forms a contiguous block and not set when the two selected rows are not adjacent. If those conditions are not met the tests would fail, indeed, Moq framework would throw exceptions.

We finish this post by showing the true implementation of the ViewModel. We do not provide the details of the method MoveAllLeft and MoveAllRight they can be found on the github (they probably can be reviewed and shortened) .

To conclude, we have shown the basic ingredients for the testing of a ViewModel, this tests suite can be extended to complete a strong code coverage (there are many corner cases in our situation). Not also, that the MVVM pattern allows you to test the command, for example the SaveClick. Thanks to the Moq VerifySet method, you can check that the setter on the UserBet property for the mock Mock<IChampionship> is called (see project on github).

All tests running successfully

All tests running successfully