문제

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 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.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top