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

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
using System;
using System.ComponentModel;
using System.IO;
using Catel.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Catel.Test.Data
{
    [TestClass]
    public class DataObjectBaseTest
    {
        #region Variables
        private FilesHelper _filesHelper = new FilesHelper();
        #endregion

        #region Initialization and cleanup
        /// <summary>
        /// Cleans up.
        /// </summary>
        [TestCleanup]
        public void CleanUp()
        {
            if (_filesHelper != null)
            {
                _filesHelper.CleanUp();
                _filesHelper = null;
            }
        }
        #endregion

        #region Equal tests
        /// <summary>
        /// Tests the Equals method 1 level deep.
        /// </summary>
        [TestMethod]
        public void EqualsLevel1()
        {
            // Create 2 objects
            var obj1 = DataObjectBaseTestHelper.CreateIniEntryObject();
            var obj2 = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Equals
            Assert.AreEqual(obj1, obj2);
        }

        /// <summary>
        /// Tests the Equals method 2 level deep.
        /// </summary>
        [TestMethod]
        public void EqualsLevel2()
        {
            // Create 2 objects
            var obj1 = DataObjectBaseTestHelper.CreateIniFileObject();
            var obj2 = DataObjectBaseTestHelper.CreateIniFileObject();

            // Equals
            Assert.AreEqual(obj1, obj2);
        }

        /// <summary>
        /// Tests the Equals method 3 level deep.
        /// </summary>
        [TestMethod]
        public void EqualsLevel3()
        {
            // Create 2 objects
            var obj1 = DataObjectBaseTestHelper.CreateComputerSettingsObject();
            var obj2 = DataObjectBaseTestHelper.CreateComputerSettingsObject();

            // Equals
            Assert.AreEqual(obj1, obj2);
        }

        [TestMethod]
        public void Equals_AreNotEqual()
        {
            // Create 2 objects
            var obj1 = DataObjectBaseTestHelper.CreateComputerSettingsObject();
            var obj2 = DataObjectBaseTestHelper.CreateIniFileObject();

            // Equals
            Assert.AreNotEqual(obj1, obj2);
        }
        #endregion

        #region Parent/child tests
        /// <summary>
        /// Tests the parent and child relations.
        /// </summary>
        [TestMethod]
        public void TestParentAndChildRelationsWhenCreating()
        {
            Parent parent = new Parent("Parent");
            Child child = parent.CreateChild("Child");

            Assert.AreEqual(parent, ((IParent)child).Parent);
        }

#if !SILVERLIGHT
        /// <summary>
        /// Tests the parent and child relations after deserialization.
        /// </summary>
        [TestMethod]
        public void TestParentAndChildRelationsWhenBinaryDeserializing()
        {
            Parent parent = new Parent("Parent");
            Child child = parent.CreateChild("Child");

            Assert.AreEqual(((IParent)child).Parent, parent);

            string fileName = _filesHelper.GetTempFileName();
            parent.Save(fileName);
            var loadedParent = SavableDataObjectBase<Parent>.Load(fileName);

            Assert.AreEqual(parent, ((IParent)loadedParent.Children[0]).Parent);
        }
#endif

        /// <summary>
        /// Tests the parent and child relations after deserialization.
        /// </summary>
        [TestMethod]
        public void TestParentAndChildRelationsWhenXmlDeserializing()
        {
            Parent parent = new Parent("Parent");
            Child child = parent.CreateChild("Child");

            Assert.AreEqual(((IParent)child).Parent, parent);

            Parent loadedParent;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                parent.Save(memoryStream, SerializationMode.Xml);

                memoryStream.Position = 0L;

                loadedParent = SavableDataObjectBase<Parent>.Load(memoryStream, SerializationMode.Xml);
            }

            Assert.AreEqual(parent, ((IParent)loadedParent.Children[0]).Parent);
        }
        #endregion

        #region Multiple inheritance tests
        /// <summary>
        /// Creates the and verify properties on inherited class. This test is used to determine
        /// if the properties defined in a derived class are also registered properly.
        /// </summary>
        [TestMethod]
        public void CreateAndVerifyPropertiesOnInheritedClass()
        {
            // Create extend ini entry
            ExtendedIniEntry extendedIniEntry = new ExtendedIniEntry();

            // Try to set original properties
            extendedIniEntry.Value = "MyValue";

            // Try to set new properties
            extendedIniEntry.DefaultValue = "DefaultValue";
        }
        #endregion

        #region Read-only tests
        [TestMethod]
        public void ReadOnlyTest()
        {
            // Declare variables
            const string testValue = "new value that shouldn't exist";
            string originalValue, actualValue;

            IniEntry iniEntry = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Test whether the object can be set to read-only
            originalValue = iniEntry.Value;
            iniEntry.SetReadOnly(true);
            iniEntry.Value = testValue;
            actualValue = iniEntry.Value;
            Assert.AreEqual(originalValue, actualValue);

            // Test whether the object can be set to edit mode again
            iniEntry.SetReadOnly(false);
            iniEntry.Value = testValue;
            actualValue = iniEntry.Value;
            Assert.AreEqual(testValue, actualValue);
        }
        #endregion

        #region Validation
        [TestMethod]
        public void ValidationWithWarnings()
        {
            // Create object
            ObjectWithValidation validationObject = new ObjectWithValidation();

            // Check if the object now has warnings
            Assert.AreEqual(false, validationObject.HasWarnings);
            Assert.AreEqual(false, validationObject.HasErrors);
            Assert.AreEqual(0, validationObject.FieldWarningCount);
            Assert.AreEqual(0, validationObject.FieldErrorCount);
            Assert.AreEqual(0, validationObject.BusinessRuleWarningCount);
            Assert.AreEqual(0, validationObject.BusinessRuleErrorCount);

            // Now set a field warning and check it
            validationObject.ValueToValidate = ObjectWithValidation.ValueThatCausesFieldWarning;
            Assert.AreEqual(true, validationObject.HasWarnings);
            Assert.AreEqual(false, validationObject.HasErrors);
            Assert.AreEqual(1, validationObject.FieldWarningCount);
            Assert.AreEqual(0, validationObject.FieldErrorCount);
            Assert.AreEqual(0, validationObject.BusinessRuleWarningCount);
            Assert.AreEqual(0, validationObject.BusinessRuleErrorCount);

            // Now set a business warning and check it
            validationObject.ValueToValidate = ObjectWithValidation.ValueThatCausesBusinessWarning;
            Assert.AreEqual(true, validationObject.HasWarnings);
            Assert.AreEqual(false, validationObject.HasErrors);
            Assert.AreEqual(0, validationObject.FieldWarningCount);
            Assert.AreEqual(0, validationObject.FieldErrorCount);
            Assert.AreEqual(1, validationObject.BusinessRuleWarningCount);
            Assert.AreEqual(0, validationObject.BusinessRuleErrorCount);

            // Clear warning
            validationObject.ValueToValidate = ObjectWithValidation.ValueThatHasNoWarningsOrErrors;
            Assert.AreEqual(false, validationObject.HasWarnings);
            Assert.AreEqual(false, validationObject.HasErrors);
            Assert.AreEqual(0, validationObject.FieldWarningCount);
            Assert.AreEqual(0, validationObject.FieldErrorCount);
            Assert.AreEqual(0, validationObject.BusinessRuleWarningCount);
            Assert.AreEqual(0, validationObject.BusinessRuleErrorCount);
        }

        [TestMethod]
        public void ValidationWithErrors()
        {
            // TODO: fix
        }
        #endregion

#if !SILVERLIGHT
        #region Allow non serializable members tests
        [TestMethod]
        [ExpectedException(typeof(InvalidPropertyException), "object should crash because it contains a non-serializable value, but is not decorated with the AllowNonSerializableMembersAttribute")]
        public void ObjectWithoutAllowNonSerializableAttribute()
        {
            var obj = new ObjectWithNonSerializableMembers();
        }

        [TestMethod]
        public void ObjectWithAllowNonSerializableAttribute()
        {
            var obj = new ObjectWithNonSerializableMembersDecoratedWithAllowNonSerializableMembersAttribute();
        }
        #endregion
#endif

        #region IClonable tests
        /// <summary>
        /// Tests the deep-clone functionality for 1 level deep.
        /// </summary>
        public void CloneLevel1()
        {
            // Create object
            var obj = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Clonse
            var clonedObj = obj.Clone();

            // Make sure the objects are equal
            Assert.AreEqual(obj, clonedObj);
        }

        /// <summary>
        /// Tests the deep-clone functionality for 2 levels deep.
        /// </summary>
        public void CloneLevel2()
        {
            // Create object
            var obj = DataObjectBaseTestHelper.CreateIniFileObject();

            // Clonse
            var clonedObj = obj.Clone();

            // Make sure the objects are equal
            Assert.AreEqual(obj, clonedObj);
        }

        /// <summary>
        /// Tests the deep-clone functionality for 3 levels deep.
        /// </summary>
        public void CloneLevel3()
        {
            // Create object
            var obj = DataObjectBaseTestHelper.CreateComputerSettingsObject();

            // Clonse
            var clonedObj = obj.Clone();

            // Make sure the objects are equal
            Assert.AreEqual(obj, clonedObj);
        }
        #endregion

        #region IDisposable tests
        [TestMethod]
        public void UninitializedCallWithoutDirectDispose()
        {
            // Declare variables
            IniEntry iniEntry = new IniEntry();

            // Set to null
            iniEntry = null;
        }

        [TestMethod]
        public void UninitializedCallWithDirectDispose()
        {
            // Declare variables
            IniEntry iniEntry = new IniEntry();

            // Dispose
            iniEntry.Dispose();
        }
        #endregion

        #region IEditableObject tests
        [TestMethod]
        public void EditAndCancelChanges()
        {
            // Get value
            var iniEntry = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Set the value we expect
            iniEntry.Value = "MyOldValue";

            // Begin edit
            iniEntry.BeginEdit();

            // Change value
            iniEntry.Value = "MyNewValue";

            // Cancel edit
            iniEntry.CancelEdit();

            // Compare
            Assert.AreEqual("MyOldValue", iniEntry.Value);
        }

        [TestMethod]
        public void EditAndCancelChanges_ObjectWithCustomType()
        {
            // Get value
            var obj = new ObjectWithCustomType();

            // Set the value we expect
            obj.Gender = Gender.Female;

            // Begin edit
            obj.BeginEdit();

            // Change value
            obj.Gender = Gender.Male;

            // Cancel edit
            obj.CancelEdit();

            // Compare
            Assert.AreEqual(Gender.Female, obj.Gender);
        }

        [TestMethod]
        public void EditAndApplyChanges()
        {
            // Get value
            var iniEntry = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Set the value we expect
            iniEntry.Value = "MyOldValue";

            // Begin edit
            iniEntry.BeginEdit();

            // Change value
            iniEntry.Value = "MyNewValue";

            // End edit
            iniEntry.EndEdit();

            // Compare
            Assert.AreEqual("MyNewValue", iniEntry.Value);
        }

        [TestMethod]
        public void EditAndApplyChanges_ObjectWithCustomType()
        {
            // Get value
            var obj = new ObjectWithCustomType();

            // Set the value we expect
            obj.Gender = Gender.Female;

            // Begin edit
            obj.BeginEdit();

            // Change value
            obj.Gender = Gender.Male;

            // End edit
            obj.EndEdit();

            // Compare
            Assert.AreEqual(Gender.Male, obj.Gender);
        }
        #endregion

#if !SILVERLIGHT
        #region INotifyPropertyChanging tests
        /// <summary>
        /// Tests whether INotifyPropertyChanging is implemented correctly.
        /// </summary>
        [TestMethod]
        public void NotifyPropertyChanging()
        {
            // Create object
            var obj = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Get variable
            bool isInvoked = false;

            // Subscribe
            obj.PropertyChanging += delegate(object sender, PropertyChangingEventArgs e)
            {
                // If we were invoked, exit (we only want to check the first event)
                if (isInvoked)
                {
                    return;
                }

                // Invoked
                isInvoked = true;

                // Check property
                if (string.Compare(e.PropertyName, "Value") != 0)
                {
                    Assert.Fail("Wrong PropertyChanging property name");
                }
            };

            // Change value
            obj.Value = "MyNewValue";

            // Check if invoked);
            if (!isInvoked)
            {
                Assert.Fail("PropertyChanging was not invoked");
            }
        }
        #endregion
#endif

        #region INotifyPropertyChanged tests
        /// <summary>
        /// Tests whether INotifyPropertyChanged is implemented correctly.
        /// </summary>
        [TestMethod]
        public void NotifyPropertyChanged()
        {
            // Create object
            var obj = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Get variable
            bool isInvoked = false;

            // Subscribe
            obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
                                    {
                                        // Invoked
                                        isInvoked = true;

                                        // Check property
                                        if (string.Compare(e.PropertyName, "Value") != 0)
                                        {
                                            Assert.Fail("Wrong PropertyChanged property name");
                                        }
                                    };

            // Change value
            obj.Value = "MyNewValue";

            // Check if invoked);
            if (!isInvoked)
            {
                Assert.Fail("PropertyChanged was not invoked");
            }
        }
        #endregion

        #region IDataErrorInfo tests
        /// <summary>
        /// Tests whether IDataErrorInfo is implemented correctly.
        /// </summary>
        [TestMethod]
        public void IDataErrorInfo()
        {
            // Create object
            var obj = DataObjectBaseTestHelper.CreateIniEntryObject();

            // Set an error
            obj.Value = string.Empty;

            // Validate the object
            obj.Validate();

            // Make sure that the error is raised
            Assert.IsFalse(string.IsNullOrEmpty(((IDataErrorInfo)obj)["Value"]));
        }
        #endregion

        #region IsDirty with children test
        [TestMethod]
        public void IsDirtyWithChildrenWhenSavingChild()
        {
            // Create a collection
            var computerSettings = DataObjectBaseTestHelper.CreateComputerSettingsObject();
            SaveObjectToMemoryStream(computerSettings);
            Assert.IsFalse(computerSettings.IsDirty);

            // Make a chance in the lowest level
            computerSettings.IniFileCollection[0].IniEntryCollection[0].Value = "is dirty should be enabled now";
            Assert.IsTrue(computerSettings.IniFileCollection[0].IniEntryCollection[0].IsDirty);
            Assert.IsTrue(computerSettings.IsDirty);

            // Save the lowest level (so the parent stays dirty)
            SaveObjectToMemoryStream(computerSettings.IniFileCollection[0].IniEntryCollection[0]);
            Assert.IsFalse(computerSettings.IniFileCollection[0].IniEntryCollection[0].IsDirty);
            Assert.IsTrue(computerSettings.IsDirty);
        }

        [TestMethod]
        public void IsDirtyWithChildrenWhenSavingParent()
        {
            // Create a collection
            var computerSettings = DataObjectBaseTestHelper.CreateComputerSettingsObject();
            SaveObjectToMemoryStream(computerSettings);
            Assert.IsFalse(computerSettings.IsDirty);

            // Make a chance in the lowest level
            computerSettings.IniFileCollection[0].IniEntryCollection[0].Value = "is dirty should be enabled now";
            Assert.IsTrue(computerSettings.IniFileCollection[0].IniEntryCollection[0].IsDirty);
            Assert.IsTrue(computerSettings.IsDirty);

            // Save the top level
            SaveObjectToMemoryStream(computerSettings);
            Assert.IsFalse(computerSettings.IniFileCollection[0].IniEntryCollection[0].IsDirty);
            Assert.IsFalse(computerSettings.IsDirty);
        }
        #endregion

        /// <summary>
        /// Saves the object to memory stream so the <see cref="IDataObjectBase.IsDirty"/> property is set to false.
        /// </summary>
        /// <param name="obj">The object.</param>
        private static void SaveObjectToMemoryStream(ISavableDataObjectBase obj)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                obj.Save(memoryStream);
            }
        }
    }
}

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
Web02 | 2.8.140827.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