Unit testing events with anonymous methods

written by Ryan Olshan on Friday, May 16 2008

For a side project, I was unit testing a class with custom events and needed a way to test those events. Anonymous methods makes unit testing of events easy. The below example is simple, but demonstrates how easy it is to unit test events with anonymous methods.

using System;

using NUnit.Framework;

 

namespace MyNamespace

{

    public class MyBusinessObjectEventArgs : EventArgs

    {

        public MyBusinessObject MyBusinessObject;

    }

 

    public class MyBusinessObject

    {

        public int ID { get; set; }

        public string Name { get; set; }

 

        public delegate void MyBusinessObjectEventHandler(MyBusinessObjectEventArgs eventArgs);

        public event MyBusinessObjectEventHandler MyBusinessObjectChanged;

 

        public void DoSomething()

        {

            //Code here

            if (MyBusinessObjectChanged != null)

            {

                MyBusinessObjectChanged(new MyBusinessObjectEventArgs { MyBusinessObject = this });

            }

        }

    }

 

    [TestFixture]

    public class MyBusinessObjectUnitTests

    {

        [Test]

        public void EventTest()

        {

            MyBusinessObject actualObject = new MyBusinessObject

                {

                    ID = 2,

                    Name = "Ryan Olshan"

                };

            MyBusinessObject expectedObject = null;

            actualObject.MyBusinessObjectChanged += delegate(MyBusinessObjectEventArgs eventArgs)

            {

                expectedObject = eventArgs.MyBusinessObject;

            };

            actualObject.DoSomething();

            Assert.IsNotNull(expectedObject);

            Assert.AreSame(expectedObject, actualObject);

        }

    }

}

Kick this post on .NET Kicks

Similar Posts

  1. C# GridView Sorting/Paging w/o a DataSourceControl DataSource
  2. Implicit and Explicit Operators in C#
  3. NUnitForms GenericControlTester

Post a comment