Exception Specs

5 views
Skip to first unread message

bjdweck

unread,
Oct 20, 2009, 3:22:20 AM10/20/09
to machine_users
How are you guys handling specifications for throwing exceptions? My
first attempt was ugly and painful:

[Subject("Changing Sort Order")]
public class
When_changing_sort_order_does_not_include_all_annual_seasons :
With_service_container
{
static Exception _exception;

Establish context = () =>
_seasonRegistry.AddAnnualSeasons(new[] { "Winter",
"Spring" });

Because of = () =>
{
try { _seasonsService.UpdateAnnualSeasonsSortOrder(new[]
{ "Spring" }); }
catch (Exception exception) { _exception = exception; }
};

It indicates_an_error = () =>
_exception.ShouldNotBeNull();

It indicates_invalid_operation = () =>
(_exception as RulesException).ShouldNotBeNull();
}

Then I created some extension methods and started doing this:

[Subject("Adding Collection - Service")]
public class When_adding_a_collection_for_a_non_existant_season :
With_service_container
{
static TestDelegate _serviceCall;

Because of = () =>
{ _serviceCall = () => _seasonsService.AddCollection("New
Collection", "Winter 2009"); };

It throws_a_rules_exception = () =>
_serviceCall.ShouldThrow<RulesException>();

It indicates_that_season_was_not_found = () =>
_serviceCall.ExpectThatException<RulesException>
().Errors.First()
.ErrorMessage.ShouldEqual("Cannot create collection:
the season 'Winter 2009' was not found.");
}

I think it's neater and it conveys the intent much better.

Thoughts?

Aaron Jensen

unread,
Oct 20, 2009, 3:26:16 AM10/20/09
to machine_users
There's a Catch.Exception(()=>code.ThatThrows()) API that returns the
exception caught. I generally just do this in the Because and assert
on it in the It.
Reply all
Reply to author
Forward
0 new messages