如何解决如何在 FluentAssertions 中使用“Which”?
我正在使用 fluent 断言并且我有这个测试:
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`
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。