Thursday, April 14, 2005

Clean unit tests with anonymous methods

Assume you are working with the following class that contains the validation rule that an ExpenseReport cannot have a week ending date less than today. The expected behavior is that when Validate is called an event will be fired if any data in the object is invalid. Anyone interested in specific errors can choose to subscribe to a specific event.

public class ExpenseReport
{
private readonly DateTime _weekEndingDate;
public event ErrorEventHandler InvalidWeekEndingDate;
public delegate void ErrorEventHandler();

public ExpenseReport(DateTime weekEndingDate)
{
_weekEndingDate = weekEndingDate;
}

public DateTime WeekEndingDate
{
get { return _weekEndingDate; }
}

public void Validate()
{
if (_weekEndingDate < DateTime.Today)
{
InvalidWeekEndingDate();
}
}
}

Testing this class becomes easy and clean with NUnit and anonymous methods:
[TestFixture]
public class ExpenseReportTests
{
[Test]
public void ValidExpenseReport()
{
ExpenseReport report = new ExpenseReport(DateTime.Today.AddDays(2));
report.InvalidWeekEndingDate += delegate { Assert.Fail(); };
report.Validate();
}

[Test]
public void InvalidWeekEndingDateReport()
{
bool methodCalled = false;
ExpenseReport report = new ExpenseReport(DateTime.Today.AddDays(-2));
report.InvalidWeekEndingDate += delegate { methodCalled = true; };
report.Validate();
Assert.IsTrue(methodCalled);
}
}
Post a Comment