我正在使用流畅的断言,并且我有这样的测试:
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?)
我哪里做错了?
发布于 2021-05-06 18:14:47
这里的问题是.NotBeNull()
不是泛型的(它是ObjectAssertions
而不是GenericObjectAssertions
上的扩展),所以它不能将类型信息链接到以后的调用。
我个人认为这是库设计中的一个缺陷,但通过用.BeOfType<T>()
替换.NotBeNull()
很容易解决这个问题:
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`
https://stackoverflow.com/questions/67423715
复制相似问题