1

我有一些代码断言调用方法时引发异常,然后断言异常的各种属性:

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

我想将Assert.Throws<T>调用转换为使用Assert.That语法,因为这是我个人的偏好:

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

但是,我不知道如何从中返回异常,所以我可以执行后续的属性断言。有任何想法吗?

4

1 回答 1

1

不幸的是,我不认为你可以Assert.That用来返回异常,如Assert.Throws. 但是,您仍然可以使用以下任一方式以比您的第一个示例更流畅的风格进行编程:

选项1(最流利/可读)

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

选项 2

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

优点缺点:

  • 缺点是硬编码属性名称。
  • 好处是你有一个连续流畅的表达式,而不是把它分成 3 个单独的表达式。使用Assert.That-like 语法的重点是它具有流畅的可读性。
于 2012-03-28T12:25:25.663 回答