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?
Unfortunately, I don't think you can use
Assert.That
to return the exception likeAssert.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)
Option 2
Pros/Cons:
Assert.That
-like syntax is for it's fluent readability.