1

I have some code which asserts an exception is thrown when a method is called, and then asserts various properties on the exception:

var ex = Assert.Throws<MyCustomException>(() => MyMethod());
Assert.That(ex.Property1, Is.EqualTo("Some thing");
Assert.That(ex.Property2, Is.EqualTo("Some thing else");

I'd like to convert the Assert.Throws<T> call to use the Assert.That syntax, as that is my personal preference:

Assert.That(() => MyMethod(), Throw.Exception.TypeOf<MyCustomException>());

However, I can't figure out how to return the exception from this, so I can perform the subsequent property assertions. Any ideas?

MPritchard
  • 7,031
  • 7
  • 28
  • 40

1 Answers1

1

Unfortunately, I don't think you can use Assert.That to return the exception like Assert.Throws. You could, however, still program in a more fluent style than your first example using either of the following:

Option 1 (most fluent/readable)

Assert.That(() => MyMethod(), Throws.Exception.TypeOf<MyCustomException>()
    .With.Property("Property1").EqualTo("Some thing")
    .With.Property("Property2").EqualTo("Some thing else"));

Option 2

Assert.Throws(Is.Typeof<MyCustomException>()
    .And.Property( "Property1" ).EqualTo( "Some thing")
    .And.Property( "Property2" ).EqualTo( "Some thing else"),
    () => MyMethod());

Pros/Cons:

  • The downside is hard-coding property names .
  • The upside is you have a single continuous fluent expression instead of breaking it up into 3 separate expressions. The point of using Assert.That-like syntax is for it's fluent readability.
Matt
  • 14,353
  • 5
  • 53
  • 65
  • Cheers. I find that when I chain constraints together, I loose the detail about which constraint cause the assertion to fail. I also find the separate constraints clearer as to what each statement is checking for. Looks like I'm going to stick with my original after all :( – MPritchard Mar 28 '12 at 15:31
  • @MPritch, those are very valid points and I didn't realize you lost detail about which constraint would cause the fail. Thanks for pointing that out. – Matt Mar 29 '12 at 12:22