Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Catel - Part 4 of n: Unit testing with Catel

, 28 Jan 2011
This article explains how to write unit tests for MVVM using Catel.
Catel-04_01-unittesting.zip
src
Catel.Articles.04 - Unit testing
Models
Properties
Settings.settings
Resources
Images
add.png
delete.png
edit.png
group.png
UI
Data
Converters
ViewModels
Windows
Catel.Articles.04 - Unit testing.Test
Models
Properties
UI
ViewModels
Catel.Articles.Base
Data
Attributes
Properties
Settings.settings
Resources
Images
CatenaLogic.png
Preview.png
Run.png
ShowCode.png
UI
Controls
Helpers
ViewModels
Windows
Catel.Core
Attributes
ClassDiagrams
DataObjectBase.cd
SavableDataObjectBase.cd
Collections
Helpers
ComponentModel
Data
Attributes
Exceptions
Interfaces
Diagnostics
Extensions
Helpers
Exceptions
Helpers
IO
Exceptions
IoC
LLBLGen
Log4net
Appender
Extensions
Helpers
MVVM
Commands
Interfaces
Exceptions
Services
EventArgs
Exceptions
Interfaces
ViewModels
Attributes
Interfaces
Properties
Reflection
Exceptions
Extensions
Helpers
Runtime
Serialization
Attributes
Helpers
Security
Cryptography
Helpers
Catel.Examples.Models
Properties
Catel.Examples.PersonApplication
Properties
Settings.settings
Resources
Images
add.png
delete.png
edit.png
group.png
UI
Data
Converters
ViewModels
Windows
Catel.Examples.Silverlight
Properties
Resources
Images
add.png
delete.png
edit.png
group.png
UI
Data
Converters
Pages
ViewModels
Windows
Catel.Examples.Silverlight.Web
Catel.Examples.Silverlight.Web.csproj.user
ClientBin
Properties
Catel.FxCop
Catel.Silverlight
Diagnostics
log4net
Core
MVVM
Commands
Services
ViewModels
Properties
Catel.Core
Catel.Windows
Reflection
Themes
Generic
Assets
Old
Windows
Controls
Data
Converters
Helpers
Helpers
Catel.Silverlight.Test
Properties
Catel.Silverlight.Test.Web
Catel.Silverlight.Test.Web.csproj.user
ClientBin
Properties
Catel.snk
Catel.Templates.WpfApplication
Properties
Settings.settings
UI
Controls
ViewModels
Windows
Catel.Templates.WpfItemTemplates
Properties
UI
Controls
ViewModels
Windows
Catel.Test
Collections
Convert
Data
Helpers
IO
MVVM
UI
ViewModels
Properties
Reflection
Runtime
Serialization
Security
Cryptography
Test References
Catel.Windows.accessor
Windows
Data
Converters
Catel.vsmdi
Catel.Windows
ClassDiagrams
ViewModelBase.cd
Collections
Extensions
Helpers
MVVM
Commands
Services
Test
UI
ViewModels
Properties
Settings.settings
Resources
Images
Add.png
ClearOutput.png
Edit.png
Error.png
Loading.gif
Preview.png
Remove.png
Save.png
TipOfTheDay.png
Warning.png
Themes
Aero
ExpressionDark
Assets
Generic
Assets
Controls
Jetpack
Assets
background.png
Old
SunnyOrange
Assets
Windows
Controls
Extensions
LinkLabel
StackGrid
Data
Converters
Helpers
Documents
Extensions
Extensions
Helpers
Input
Markup
Media
Effects
EmptyEffect
EmptyEffect.fx
EmptyEffect.ps
EmptyEffect.fx
GrayscaleEffect
GrayscaleEffect.fx
GrayscaleEffect.ps
Extensions
Imaging
Extensions
Windows
DataWindow
TipOfTheDay
Local.testsettings
Settings.StyleCop
TraceAndTestImpact.testsettings
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UIVisualizerService.cs" company="Catel development team">
//   Copyright (c) 2008 - 2011 Catel development team. All rights reserved.
// </copyright>
// <summary>
//   Service to show modal or non-modal popup windows.
//   This implementation of the <see cref="IUIVisualizerService" /> automatically adds all instances of the
//   <see cref="DataWindow{TViewModel}" /> class that are found in the current application domain.
//   All other windows will have to be registered manually.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using Catel.Windows;
using Catel.Windows.Properties;
using log4net;

namespace Catel.MVVM.Services
{
    /// <summary>
    /// Service to show modal or non-modal popup windows.
    /// 
    /// This implementation of the <see cref="IUIVisualizerService"/> automatically adds all instances of the
    /// <see cref="DataWindow{TViewModel}"/> class that are found in the current application domain.
    /// 
    /// All other windows will have to be registered manually.
    /// </summary>
    /// <remarks>
    /// This implementation is based on the implementation that can be found in Cinch 
    /// (see http://www.codeproject.com/KB/WPF/CinchIII.aspx#PopServ). 
    /// </remarks>
    public class UIVisualizerService : ViewModelServiceBase, IUIVisualizerService
    {
        #region Variables
        private readonly Dictionary<string, Type> _registeredWindows = new Dictionary<string, Type>();
        #endregion

        #region Constructor & destructor
        /// <summary>
        /// Initializes a new instance of the <see cref="UIVisualizerService"/> class.
        /// </summary>
        public UIVisualizerService()
        {
            RegisterTypesAutomatically();
        }
        #endregion

        #region Properties
        #endregion

        #region Methods
        /// <summary>
        /// Registers the specified view model and the window type. This way, Catel knowns what
        /// window to show when a specific view model window is requested.
        /// </summary>
        /// <param name="viewModelType">Type of the view model.</param>
        /// <param name="windowType">Type of the window.</param>
        /// <exception cref="ArgumentException">when <paramref name="viewModelType"/> does not implement <see cref="IViewModel"/>.</exception>
        /// <exception cref="ArgumentException">when <paramref name="windowType"/> is not of type <see cref="Window"/>.</exception>
        public void Register(Type viewModelType, Type windowType)
        {
            if (viewModelType.GetInterface(typeof(IViewModel).FullName) == null)
            {
                throw new ArgumentException(Exceptions.ArgumentMustImplementIViewModelInterface, "viewModelType");
            }

            Register(viewModelType.FullName, windowType);
        }

        /// <summary>
        /// Registers the specified view model and the window type. This way, Catel knowns what
        /// window to show when a specific view model window is requested.
        /// </summary>
        /// <param name="name">Name of the registered window.</param>
        /// <param name="windowType">Type of the window.</param>
        /// <exception cref="ArgumentException">when <paramref name="name"/> is <c>null</c> or empty.</exception>
        /// <exception cref="ArgumentException">when <paramref name="windowType"/> is not of type <see cref="Window"/>.</exception>
        public void Register(string name, Type windowType)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(Exceptions.ArgumentCannotBeNullOrEmpty, "name");
            }

            if (windowType.IsAssignableFrom(typeof(Window)))
            {
                throw new ArgumentException(Exceptions.ArgumentMustBeOfTypeWindow, "windowType");
            }

            lock (_registeredWindows)
            {
                if (_registeredWindows.ContainsKey(name))
                {
                    throw new InvalidOperationException(Exceptions.ViewModelAlreadyRegistered);
                }

                _registeredWindows.Add(name, windowType);

                Log.Debug(TraceMessages.RegisteredViewModelInUIVisualizerService, name, windowType.FullName);
            }
        }

        /// <summary>
        /// This unregisters the specified view model.
        /// </summary>
        /// <param name="viewModelType">Type of the view model to unregister.</param>
        /// <returns>
        /// 	<c>true</c> if the view model is unregistered; otherwise <c>false</c>.
        /// </returns>
        public bool Unregister(Type viewModelType)
        {
            return Unregister(viewModelType.FullName);
        }

        /// <summary>
        /// This unregisters the specified view model.
        /// </summary>
        /// <param name="name">Name of the registered window.</param>
        /// <returns>
        /// 	<c>true</c> if the view model is unregistered; otherwise <c>false</c>.
        /// </returns>
        public bool Unregister(string name)
        {
            lock (_registeredWindows)
            {
                bool result = _registeredWindows.Remove(name);
                if (result)
                {
                    Log.Debug(TraceMessages.UnregisteredViewModelInUIVisualizerService, name);
                }

                return result;
            }
        }

        /// <summary>
        /// Shows a window that is registered with the specified view model in a non-modal state.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns>
        /// 	<c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentNullException">when <paramref name="viewModel"/> is <c>null</c>.</exception>
        /// <exception cref="ViewModelNotRegisteredException">when <paramref name="viewModel"/> is not registered by the <see cref="Register(System.Type,System.Type)"/> method first.</exception>
        public bool Show(IViewModel viewModel)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }

            return Show(viewModel.GetType().FullName, viewModel);
        }

        /// <summary>
        /// Shows a window that is registered with the specified name in a non-modal state.
        /// </summary>
        /// <param name="name">The name that the window is registered with.</param>
        /// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
        /// <returns>
        /// 	<c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentException">when <paramref name="name"/> is <c>null</c> or empty.</exception>
        public bool Show(string name, object data)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(Exceptions.ArgumentCannotBeNullOrEmpty, "name");
            }

            return Show(name, data, null);
        }

        /// <summary>
        /// Shows a window that is registered with the specified view model in a non-modal state.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
        /// <returns>
        /// 	<c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentNullException">when <paramref name="viewModel"/> is <c>null</c>.</exception>
        /// <exception cref="ViewModelNotRegisteredException">when <paramref name="viewModel"/> is not registered by the <see cref="Register(System.Type,System.Type)"/> method first.</exception>
        public bool Show(IViewModel viewModel, EventHandler<UICompletedEventArgs> completedProc)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }

            return Show(viewModel.GetType().FullName, viewModel, completedProc);
        }

        /// <summary>
        /// Shows a window that is registered with the specified view model in a non-modal state.
        /// </summary>
        /// <param name="name">The name that the window is registered with.</param>
        /// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
        /// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
        /// <returns>
        /// 	<c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentException">when <paramref name="name"/> is <c>null</c> or empty.</exception>
        /// <exception cref="WindowNotRegisteredException">when <paramref name="name"/> is not registered by the <see cref="Register(string,System.Type)"/> method first.</exception>
        public bool Show(string name, object data, EventHandler<UICompletedEventArgs> completedProc)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(Exceptions.ArgumentCannotBeNullOrEmpty, "name");
            }

            lock (_registeredWindows)
            {
                if (!_registeredWindows.ContainsKey(name))
                {
                    throw new WindowNotRegisteredException(name);
                }
            }

            Window window = CreateWindow(name, data, completedProc, false);
            if (window != null)
            {
                window.Show();
            }

            return (window != null);
        }

        /// <summary>
        /// Shows a window that is registered with the specified view model in a modal state.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns>
        /// Nullable boolean representing the dialog result.
        /// </returns>
        /// <exception cref="ArgumentNullException">when <paramref name="viewModel"/> is <c>null</c>.</exception>
        /// <exception cref="WindowNotRegisteredException">when <paramref name="viewModel"/> is not registered by the <see cref="Register(string,System.Type)"/> method first.</exception>
        public bool? ShowDialog(IViewModel viewModel)
        {
            return ShowDialog(viewModel.GetType().FullName, viewModel, null);
        }

        /// <summary>
        /// Shows a window that is registered with the specified view model in a modal state.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
        /// <returns>
        /// Nullable boolean representing the dialog result.
        /// </returns>
        /// <exception cref="ArgumentNullException">when <paramref name="viewModel"/> is <c>null</c>.</exception>
        /// <exception cref="WindowNotRegisteredException">when <paramref name="viewModel"/> is not registered by the <see cref="Register(string,System.Type)"/> method first.</exception>
        public bool? ShowDialog(IViewModel viewModel, EventHandler<UICompletedEventArgs> completedProc)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }

            return ShowDialog(viewModel.GetType().FullName, viewModel, completedProc);
        }

        /// <summary>
        /// Shows a window that is registered with the specified view model in a modal state.
        /// </summary>
        /// <param name="name">The name that the window is registered with.</param>
        /// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
        /// <returns>
        /// Nullable boolean representing the dialog result.
        /// </returns>
        /// <exception cref="ArgumentException">when <paramref name="name"/> is <c>null</c> or empty.</exception>
        /// <exception cref="WindowNotRegisteredException">when <paramref name="name"/> is not registered by the <see cref="Register(string,System.Type)"/> method first.</exception>
        public bool? ShowDialog(string name, object data)
        {
            return ShowDialog(name, data, null);
        }

        /// <summary>
        /// Shows a window that is registered with the specified view model in a modal state.
        /// </summary>
        /// <param name="name">The name that the window is registered with.</param>
        /// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
        /// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
        /// <returns>
        /// Nullable boolean representing the dialog result.
        /// </returns>
        /// <exception cref="ArgumentException">when <paramref name="name"/> is <c>null</c> or empty.</exception>
        /// <exception cref="WindowNotRegisteredException">when <paramref name="name"/> is not registered by the <see cref="Register(string,System.Type)"/> method first.</exception>
        public bool? ShowDialog(string name, object data, EventHandler<UICompletedEventArgs> completedProc)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(Exceptions.ArgumentCannotBeNullOrEmpty, "name");
            }

            lock (_registeredWindows)
            {
                if (!_registeredWindows.ContainsKey(name))
                {
                    throw new WindowNotRegisteredException(name);
                }
            }

            Window window = CreateWindow(name, data, completedProc, true);
            if (window != null)
            {
                return window.ShowDialog();
            }

            return false;
        }

        /// <summary>
        /// This creates the WPF window from a key.
        /// </summary>
        /// <param name="name">The name that the window is registered with.</param>
        /// <param name="data">The data that will be set as data context.</param>
        /// <param name="completedProc">Callback</param>
        /// <param name="isModal">True if this is a ShowDialog request</param>
        /// <returns>The created window.</returns>
        private Window CreateWindow(string name, object data, EventHandler<UICompletedEventArgs> completedProc, bool isModal)
        {
            Type windowType;
            lock (_registeredWindows)
            {
                if (!_registeredWindows.TryGetValue(name, out windowType))
                {
                    return null;
                }
            }

            Window window = null;

            // First, try to constructor directly with the data context
            if (data != null)
            {
                ConstructorInfo constructorInfo = windowType.GetConstructor(new[] { data.GetType() });
                if (constructorInfo != null)
                {
                    window = constructorInfo.Invoke(new object[] { data }) as Window;
                }
                else
                {
                    Log.Debug(TraceMessages.NoConstructorWithViewModelInjectionFound, data.GetType());
                }
            }

            // Check if there is a window constructed
            if (window == null)
            {
                ConstructorInfo constructorInfo = windowType.GetConstructor(Type.EmptyTypes);
                if (constructorInfo == null)
                {
                    Log.Error(TraceMessages.NoInjectionOrDefaultConstructorFoundForWindow, windowType);
                    return null;
                }

                window = constructorInfo.Invoke(new object[] { }) as Window;
                if (window != null)
                {
                    window.DataContext = data;
                }
            }

            if ((window != null) && (completedProc != null))
            {
                window.Closed += (s, e) => completedProc(this, new UICompletedEventArgs(data, isModal ? window.DialogResult : null));
            }

            return window;
        }

        /// <summary>
        /// Registers the types automatically.
        /// </summary>
        private void RegisterTypesAutomatically()
        {
            Log.Debug(TraceMessages.RegisteringAllDataWindowImplementationsAutomatically);

            // Find all implementations of the DataWindow<TViewModel>
            foreach (Assembly assembly in AssemblyHelper.GetLoadedAssemblies())
            {
                try
                {
                    foreach (Type type in assembly.GetTypes())
                    {
                        try
                        {
                            if (!type.IsAbstract && (type != typeof(DataWindow<>)) && TypeHelper.IsSubclassOfRawGeneric(typeof(DataWindow<>), type))
                            {
                                Type baseType = type.BaseType;
                                while (true)
                                {
                                    if (baseType == null)
                                    {
                                        break;
                                    }

                                    // If the base type is generic and of the type we are looking for, we can stop
                                    if (baseType.IsGenericType && (baseType.GetGenericTypeDefinition() == typeof(DataWindow<>)))
                                    {
                                        break;
                                    }

                                    baseType = baseType.BaseType;
                                }

                                if (baseType == null)
                                {
                                    Log.Warn(TraceMessages.CouldNotFindGenericDefinition, type.Name);
                                    continue;
                                }

                                Type viewModelType = baseType.GetGenericArguments()[0];
                                Register(viewModelType, type);

                                Log.Debug(TraceMessages.AutomaticallyRegisteredViewModel, viewModelType.Name, type.Name);
                            }
                        }
                        catch (Exception innerEx)
                        {
                            Log.Error(innerEx, TraceMessages.FailedToRegisterType, type);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, TraceMessages.FailedToGetTypesOfAssembly, assembly.FullName);
                }
            }

            Log.Debug(TraceMessages.RegisteredAllDataWindowImplementationsAutomatically);
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Geert van Horrik
Software Developer CatenaLogic
Netherlands Netherlands
I am Geert van Horrik, and I have studied Computer Science in the Netherlands.
 
I love to write software using .NET (especially the combination of WPF and C#). I am also the lead developer of Catel, an open-source application development framework for WPF, Silverlight, WP7 and WinRT with the focus on MVVM.
 
I have my own company since January 1st 2007, called CatenaLogic. This company develops commercial and non-commercial software.
 
To download (or buy) applications I have written, visit my website: http://www.catenalogic.com
Follow on   Twitter

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 28 Jan 2011
Article Copyright 2011 by Geert van Horrik
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid