如何在 FluentAssertions 中使用“Which”?

gec*_*kos 3 c# fluent-assertions

我正在使用流畅的断言,并且进行了以下测试:

result.Should().NotBeNull();
result.Link.Should().Equals("https://someinvoiceurl.com");
Run Code Online (Sandbox Code Playgroud)

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

result.Should().NotBeNull()
.Which.Link.Equals("https://someinvoiceurl.com");
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

“AndConstraint”不包含“Which”的定义,并且找不到接受“AndConstraint”类型的第一个参数的可访问扩展方法“Which”(您是否缺少 using 指令或程序集引用?)

我做错了什么?

Tul*_*x86 5

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

.NotBeNull()就我个人而言,我认为这是库设计中的一个缺陷,但可以通过替换为.BeOfType<T>()以下方式轻松解决:

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

当然,如果您ThingWithLink经常对类型进行断言,则可能值得编写自定义断言,以便您可以“更流畅”:

result.Should().BeOfType<ThingWithLink>()
    .And.HaveLink("https://someinvoiceurl.com");
Run Code Online (Sandbox Code Playgroud)

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

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