如何使用Fluent Assertions来测试不等式测试中的异常?

Nat*_*ema 42 c# lambda nunit unit-testing fluent-assertions

我正在尝试使用C#中的Fluent Assertions为超过重写的运算符编写单元测试.如果其中一个对象为null,则此类中的大于运算符应该抛出异常.

通常在使用Fluent Assertions时,我会使用lambda表达式将该方法放入一个动作中.然后我会运行动作并使用action.ShouldThrow<Exception>.但是,我无法弄清楚如何将运算符放入lambda表达式.

我宁愿不使用NUnit Assert.Throws(),ThrowsConstraint或[ExpectedException]属性来保持一致性.

Kot*_*ote 67

你可以尝试这种方法.

[Test]
public void GreaterThan_NullAsRhs_ThrowsException()
{
    var lhs = new ClassWithOverriddenOperator();
    var rhs = (ClassWithOverriddenOperator) null;

    Action comparison = () => { var res = lhs > rhs; };

    comparison.Should().Throw<Exception>();
}
Run Code Online (Sandbox Code Playgroud)

它看起来不够整洁.但它的确有效.

或者两行

Func<bool> compare = () => lhs > rhs;
Action act = () => compare();
Run Code Online (Sandbox Code Playgroud)

  • `act.Should().NotThrow();` 检查是否存在异常。 (2认同)