如何使用Assert获得抛出的异常。那就是Assert.Throws

时间:2022-06-20 20:30:01

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.Throws 调用以使用Assert.That语法,因为这是我个人的偏好:

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?

但是,我无法弄清楚如何从中返回异常,因此我可以执行后续的属性断言。有任何想法吗?

1 个解决方案

#1


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:

不幸的是,我认为你不能使用Assert.That返回像Assert.Throws这样的异常。但是,您可以使用以下任一方式以比第一个示例更流畅的方式编程:

Option 1 (most fluent/readable)

选项1(最流利/可读)

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.
  • 好处是你有一个连续流畅的表达,而不是分成3个单独的表达式。使用Assert的意义。类似于语法的是它具有流畅的可读性。

#1


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:

不幸的是,我认为你不能使用Assert.That返回像Assert.Throws这样的异常。但是,您可以使用以下任一方式以比第一个示例更流畅的方式编程:

Option 1 (most fluent/readable)

选项1(最流利/可读)

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.
  • 好处是你有一个连续流畅的表达,而不是分成3个单独的表达式。使用Assert的意义。类似于语法的是它具有流畅的可读性。