FluentAssertions Asserting multiple properties of a single object

kolhapuri picture kolhapuri · Apr 21, 2017 · Viewed 9.8k times · Source

Is there a way to do something like this using FluentAssertions

response.Satisfy(r =>
    r.Property1== "something" &&
    r.Property2== "anotherthing"));

I am trying to avoid writing multiple Assert statements. This was possible with https://sharptestex.codeplex.com/ which I was using for the longest time. But SharpTestEx does not support .Net Core.

Answer

Nick N. picture Nick N. · Oct 4, 2018

The .Match() solution does not return a good error message. So if you want to have a good error and only one assert then use:

result.Should().BeEquivalentTo(new MyResponseObject()
            {
                Property1 = "something",
                Property2 = "anotherthing"
            });

Anonymous objects (use with care!)

If you want to only check certain members then use:

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

Note: You will miss (new) members when testing like this. So only use if you really want to check only certain members now and in the future. Not using the exclude option will force you to edit your test when a new property is added and that can be a good thing

Multiple asserts

Note: All given solutions gives you one line asserts. In my opinion there is nothing wrong with multiple lines of asserts as long as it is one assert functionally.

If you want this because you want multiple errors at once, consider wrapping your multi line assertions in an AssertionScope.

using (new AssertionScope())
{
    result.Property1.Should().Be("something");
    result.Property2.Should().Be("anotherthing");
}

Above statement will now give both errors at once, if they both fail.

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