【问题标题】:Fluent assertion should be greater than always pass流利的断言应该大于总是通过
【发布时间】:2023-03-27 15:04:01
【问题描述】:

我正在尝试使用以下方法测试我的收藏:

  var costByFactoryt = dataAccess.GetcostPerFactoryt(null, null);
  costByFactoryt.Count().Should().BeGreaterThan(0);
  costByFactoryt.Select(x => x.Cost.Should().BeGreaterThan(100));

但问题是,如果我把最后一行代码改成,

 costByFactoryt.Select(x => x.Cost.Should().BeGreaterThan(1000));

costingByCircuit.Select(x => x.Cost.Should().BeLessThan(100));

它仍然通过,这是错误的。

我要测试的是,所有成本都应该大于 100。

【问题讨论】:

  • 不要使用 select,而是遍历集合...
  • 将全选改为全部
  • 其实这个问题和Fluent Assertions无关

标签: c# .net unit-testing fluent-assertions


【解决方案1】:

这种方式根本行不通,因为 LINQ Select 不会迭代集合 => 没有执行您的测试代码

根据Fluent Assertions documentation

正确的语法应该是

costingByCircuit.Select(x => x.Cost).Should().OnlyContain(x => x > 100);

【讨论】:

  • OP 想用FluentAssertions测试列表中的所有项目大于100
  • 因为FluentAssertionsLINQ 是这样设计的,LINQ Select 不会迭代集合,因此不会执行测试代码
  • 您能否将其添加到答案中,即使您回答提供的解决方案也缺乏解释。
  • 更新了@Fabio,还添加了官方文档的参考链接
【解决方案2】:

那么写costByFactoryt.Select(x => x.Cost.Should().BeGreaterThan(100)); 的问题是它什么都不测试。 它创建了一个从不迭代的惰性 LINQ 表达式,即不会调用任何 BeGreaterThan

在使用 Fluent Assertions 时,您将获得最详细的失败消息,而您可以避免使用 Select,因为更多信息随后可供失败消息生成器使用。

什么时候

costByFactoryt.Select(x => x.Cost).Should().OnlyContain(x => x > 100)

失败,消息生成器将输出Cost 对象。

改为写

costByFactoryt.Should().OnlyContain(x => x.Cost > 100)

失败消息将包含所有 x 对象。

【讨论】:

    猜你喜欢
    • 2018-12-01
    • 2019-06-03
    • 2016-11-08
    • 2020-02-08
    • 2014-07-27
    • 2018-06-25
    • 2021-12-28
    • 2021-01-18
    • 2020-08-16
    相关资源
    最近更新 更多