fluent-assertions - 如何在 FluentAssertions 中使用“Which”?
问题描述
我正在使用流利的断言,我有这个测试:
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?)
我做错了什么?
解决方案
这里的问题是它.NotBeNull()
不是通用的(它是对ObjectAssertions
而不是的扩展GenericObjectAssertions
),因此它不能将类型信息链接到以后的调用。
我个人认为这是库设计中的一个缺陷,但可以通过替换为以下内容轻松.NotBeNull()
解决.BeOfType<T>()
:
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`