Unit testing events with anonymous methods
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);
}
}
}
Similar Posts
- C# GridView Sorting/Paging w/o a DataSourceControl DataSource
- Implicit and Explicit Operators in C#
- NUnitForms GenericControlTester




