52

我正在尝试使用 C# 中的流利断言为大于覆盖的运算符编写单元测试。如果任何一个对象为空,则此类中的大于运算符应该引发异常。

通常在使用 Fluent Assertions 时,我会使用 lambda 表达式将方法放入操作中。然后我会运行该操作并使用action.ShouldThrow<Exception>. 但是,我不知道如何将运算符放入 lambda 表达式中。

为了一致性起见,我宁愿不使用 NUnit 的Assert.Throws()Throws约束或[ExpectedException]属性。

4

1 回答 1

82

你可以试试这个方法。

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

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

    comparison.Should().Throw<Exception>();
}

它看起来不够整洁。但它有效。

或者分两行

Func<bool> compare = () => lhs > rhs;
Action act = () => compare();
于 2016-01-26T04:06:51.400 回答