D
David Veeneman
This post is for the benefit of the Google spider and needs no response.
How do you unit test an event handler with NUnit? An event handler is not a
test method, and Asserts in test class event handlers will not be tested.
So, if the test class is to contain event handlers, the most obvious
solution is to return values in the event args and test those results in the
test method.
But that approach couples the event to the test framework. A better
alternative is to use an anonymous delegate:
[Test]
public void TestOrderDispatchC()
{
// Create order
Order testOrder = new Order();
OrderItem testItem1 = testOrder.AddOrderItem();
testItem1.Status = ItemStatus.Undelivered;
OrderItem testItem2 = testOrder.AddOrderItem();
testItem2.Status = ItemStatus.Undelivered;
// Create anonymous delegate
DeliveryNeededEventHandler anonymousDelegate = delegate(object
sender, DeliveryNeededEventArgs e)
{
Assert.AreEqual(2, e.OrderItems.Count);
};
// Subscribe to DeliveryNeeded event
testOrder.DeliveryNeeded += anonymousDelegate;
// Dispatch order
testOrder.DispatchOrder();
// Unsubscribe from the DeliveryNeeded event
testOrder.DeliveryNeeded -= anonymousDelegate;
}
Be sure to unsubscribe from the event at the end of the method. Failing to
unsubscribe causes a memory leak (yes, you can get them in .NET). The memory
leak occurs with any delegate, not just anonymous delegates, if you don't
unsubscribe.
David Veeneman
Foresight Systems
How do you unit test an event handler with NUnit? An event handler is not a
test method, and Asserts in test class event handlers will not be tested.
So, if the test class is to contain event handlers, the most obvious
solution is to return values in the event args and test those results in the
test method.
But that approach couples the event to the test framework. A better
alternative is to use an anonymous delegate:
[Test]
public void TestOrderDispatchC()
{
// Create order
Order testOrder = new Order();
OrderItem testItem1 = testOrder.AddOrderItem();
testItem1.Status = ItemStatus.Undelivered;
OrderItem testItem2 = testOrder.AddOrderItem();
testItem2.Status = ItemStatus.Undelivered;
// Create anonymous delegate
DeliveryNeededEventHandler anonymousDelegate = delegate(object
sender, DeliveryNeededEventArgs e)
{
Assert.AreEqual(2, e.OrderItems.Count);
};
// Subscribe to DeliveryNeeded event
testOrder.DeliveryNeeded += anonymousDelegate;
// Dispatch order
testOrder.DispatchOrder();
// Unsubscribe from the DeliveryNeeded event
testOrder.DeliveryNeeded -= anonymousDelegate;
}
Be sure to unsubscribe from the event at the end of the method. Failing to
unsubscribe causes a memory leak (yes, you can get them in .NET). The memory
leak occurs with any delegate, not just anonymous delegates, if you don't
unsubscribe.
David Veeneman
Foresight Systems