【问题标题】:How to use `Which` in FluentAssertions?如何在 FluentAssertions 中使用“Which”?
【发布时间】:2021-07-29 02:22:34
【问题描述】:

我正在使用流利的断言并且我有这个测试:

            result.Should().NotBeNull();
            result.Link.Should().Equals("https://someinvoiceurl.com");

效果很好,但是当我尝试这个时

            result.Should().NotBeNull().Which.Link.Equals("https://someinvoiceurl.com");

我收到了这个错误

'AndConstraint<ObjectAssertions>' does not contain a definition for 'Which' and no accessible extension method 'Which' accepting a first argument of type 'AndConstraint<ObjectAssertions>' could be found (are you missing a using directive or an assembly reference?)

我做错了什么?

【问题讨论】:

  • 使用And 而不是Which。前者用于链接。后者是前一个断言改变了被断言对象的类型。

标签: fluent-assertions


【解决方案1】:

这里的问题是.NotBeNull() 不是通用的(它是ObjectAssertions 而不是GenericObjectAssertions 的扩展),因此它不能将类型信息链接到以后的调用。

我个人认为这是库设计中的一个缺陷,但可以通过将.NotBeNull() 替换为.BeOfType&lt;T&gt;() 来轻松解决:

result.Should().BeOfType<ThingWithLink>() // assertion fails if `result` is null
    .Which.Link.Should().Be("https://someinvoiceurl.com");

当然,如果您经常在 ThingWithLink 类型上断言,那么编写自定义断言可能是值得的,这样您就可以“更流畅”:

result.Should().BeOfType<ThingWithLink>()
    .And.HaveLink("https://someinvoiceurl.com");

如果您需要更特别的东西,您可以随时使用.BeEquivalentTo() 进行结构比较:

result.Should().NotBeNull()
    .And.BeEquivalentTo(new { Link = "https://someinvoiceurl.com" }); // ignores all members on `result` except for `result.Link`

【讨论】:

  • .BeOfType&lt;T&gt;() 为空会失败吗?
  • 正确:null 没有运行时类型,所以它不能是 T 类型。
猜你喜欢
  • 2020-01-18
  • 2020-09-16
  • 2014-12-13
  • 2022-01-21
  • 2017-12-15
  • 2019-08-25
  • 2017-06-22
  • 2014-04-04
  • 2019-07-28
相关资源
最近更新 更多