FluentAssertions断言单个对象的多个属性

kol*_*uri 10 c# fluent-assertions .net-core

有没有办法使用FluentAssertions做这样的事情

response.Satisfy(r =>
    r.Property1== "something" &&
    r.Property2== "anotherthing"));
Run Code Online (Sandbox Code Playgroud)

我试图避免编写多个Assert语句.使用https://sharptestex.codeplex.com/可以实现这一点,我使用时间最长.但SharpTestEx不支持.Net Core.

Nic*_* N. 13

.Match()解决方案不会返回正确的错误消息。因此,如果您想犯一个很好的错误并且只有一个断言,请使用:

result.Should().BeEquivalentTo(new MyResponseObject()
            {
                Property1 = "something",
                Property2 = "anotherthing"
            });
Run Code Online (Sandbox Code Playgroud)

匿名对象(请谨慎使用!

如果您只想检查某些成员,请使用:

    result.Should().BeEquivalentTo(new
            {
                Property1 = "something",
                Property2 = "anotherthing"
            }, options => options.ExcludingMissingMembers());
Run Code Online (Sandbox Code Playgroud)

多个断言

注意:所有给定的解决方案都为您提供了一条断言。我认为多行断言没有错,只要它在功能上是一个断言即可。

如果因为一次要多个错误而需要这样做,请考虑将多行断言包装在中AssertionScope

using (new AssertionScope())
{
    result.Property1.Should().Be("something");
    result.Property2.Should().Be("anotherthing");
}
Run Code Online (Sandbox Code Playgroud)

如果它们都失败了,那么上面的语句现在将立即给出这两个错误。

https://fluentassertions.com/introduction#assertion-scopes


Nko*_*osi 9

您应该能够使用通用Match断言通过谓词验证主题的多个属性

response.Should()
        .Match<MyResponseObject>((x) => 
            x.Property1 == "something" && 
            x.Property2 == "anotherthing"
        );
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码有效,但断言失败时的错误消息非常尴尬。与 FluentAssertions 通常产生的结果相差太远。我建议改用多个断言:) (4认同)