Click here to Skip to main content
11,641,211 members (61,999 online)
Click here to Skip to main content
Add your own
alternative version

Catel - Part 4 of n: Unit testing with Catel

, 28 Jan 2011 CPOL 20K 479 9
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="ReflectionExtensions.cs" company="Catel development team">
//   Copyright (c) 2008 - 2011 Catel development team. All rights reserved.
// </copyright>
// <summary>
//   Reflection extension class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Reflection;

namespace Catel.Reflection
{
	/// <summary>
	/// Reflection extension class.
	/// </summary>
	public static class ReflectionExtensions
	{
		#region Variables
        /// <summary>
        /// Cache for the properties per type.
        /// </summary>
		private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _properties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

        /// <summary>
        /// Cache for the methods per type.
        /// </summary>
		private static readonly Dictionary<Type, Dictionary<string, MethodInfo>> _methods = new Dictionary<Type, Dictionary<string, MethodInfo>>();
		#endregion

		#region Methods
		/// <summary>
		/// Gets the field info for a specific field. But, the good thing about this is that it also supports
		/// <see cref="BindingFlags.FlattenHierarchy"/> for private members in base classes.
		/// </summary>
		/// <param name="type">The type to reflect.</param>
		/// <param name="fieldName">Name of the field.</param>
		/// <param name="bindingFlags">The binding flags.</param>
		/// <returns><see cref="FieldInfo"/> or <c>null</c> if the field is not found.</returns>
		public static FieldInfo GetFieldAndAllowPrivateBaseMembers(this Type type, string fieldName, BindingFlags bindingFlags)
		{
			FieldInfo fieldInfo = null;
			bool flattenHierarchy = Enum<BindingFlags>.Flags.IsFlagSet(bindingFlags, BindingFlags.FlattenHierarchy);
			if (flattenHierarchy)
			{
				bindingFlags = Enum<BindingFlags>.Flags.ClearFlag(bindingFlags, BindingFlags.FlattenHierarchy);
			}

			while (type != null)
			{
				fieldInfo = type.GetField(fieldName, bindingFlags);

				if (flattenHierarchy)
				{
					if (fieldInfo != null)
					{
						break;
					}

					type = type.BaseType;
				}
				else
				{
					break;
				}
			}

			return fieldInfo;
		}

		/// <summary>
		/// Gets the property info for a specific property of a specific type.
		/// </summary>
        /// <param name="type">The type to reflect.</param>
		/// <param name="propertyName">Name of the property.</param>
		/// <returns><see cref="PropertyInfo"/> of the property or <c>null</c> if the property is not found.</returns>
		public static PropertyInfo GetPropertyCached(this Type type, string propertyName)
		{
			var dictionary = _properties;
			string memberName = propertyName;

			var info = GetObjectFromCache(dictionary, type, memberName);
			if (info == null)
			{
				var memberInfo = type.GetProperty(memberName);
				AddObjectToCache(dictionary, type, memberName, memberInfo);
			}

			return GetObjectFromCache(dictionary, type, memberName);
		}

		/// <summary>
		/// Gets the method for a specific type.
		/// </summary>
        /// <param name="type">The type that contains the member.</param>
		/// <param name="methodName">Name of the method.</param>
		/// <returns><see cref="MethodInfo"/> of the method or <c>null</c> if the method is not found.</returns>
		public static MethodInfo GetMethodCached(this Type type, string methodName)
		{
			var dictionary = _methods;
			string memberName = methodName;

			var info = GetObjectFromCache(dictionary, type, memberName);
			if (info == null)
			{
				var memberInfo = type.GetMethod(memberName);
				AddObjectToCache(dictionary, type, memberName, memberInfo);
			}

			return GetObjectFromCache(dictionary, type, memberName);
		}

		/// <summary>
		/// Adds an object to cache.
		/// </summary>
		/// <typeparam name="T">Type of the member.</typeparam>
		/// <param name="dictionary">The dictionary.</param>
        /// <param name="type">The type that contains the member.</param>
		/// <param name="memberName">Name of the member.</param>
		/// <param name="reflectedMember">The reflected member.</param>
		private static void AddObjectToCache<T>(Dictionary<Type, Dictionary<string, T>> dictionary, Type type, string memberName, T reflectedMember)
		{
			if (!dictionary.ContainsKey(type))
			{
				dictionary.Add(type, new Dictionary<string, T>());
			}

			if (dictionary[type].ContainsKey(memberName))
			{
				dictionary[type][memberName] = reflectedMember;
			}
			else
			{
				dictionary[type].Add(memberName, reflectedMember);
			}
		}

		/// <summary>
		/// Gets an object from cache.
		/// </summary>
		/// <typeparam name="T">Type of the member.</typeparam>
		/// <param name="dictionary">The dictionary.</param>
        /// <param name="type">The type that contains the member.</param>
		/// <param name="memberName">Name of the member.</param>
		/// <returns>object or <c>null</c> if the object does not exist in the cache.</returns>
		private static T GetObjectFromCache<T>(Dictionary<Type, Dictionary<string, T>> dictionary, Type type, string memberName) where T : class
		{
			if (!dictionary.ContainsKey(type))
			{
				dictionary.Add(type, new Dictionary<string, T>());
			}

			return dictionary[type].ContainsKey(memberName) ? dictionary[type][memberName] : null;
		}
		#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

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150731.1 | Last Updated 28 Jan 2011
Article Copyright 2011 by Geert van Horrik
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid