【问题标题】:How to use Fluent Assertions to test for exception in inequality tests?如何使用 Fluent Assertions 在不等式测试中测试异常?
【发布时间】:2016-05-02 13:55:13
【问题描述】:

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

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

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

【问题讨论】:

标签: c# unit-testing lambda nunit fluent-assertions


【解决方案1】:

你可以试试这个方法。

[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();

【讨论】:

  • act.Should().NotThrow(); 检查没有异常。
  • 我使用它来解决我的问题略有不同,因为我正在测试一个异步方法。因此,对于 async/await,您可以将 Action 替换为 Func
猜你喜欢
  • 2013-07-18
  • 2020-05-02
  • 2015-04-29
  • 1970-01-01
  • 2019-10-28
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多