Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentAssertions Asserting multiple properties of a single object

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.

like image 573
kolhapuri Avatar asked Apr 21 '17 13:04

kolhapuri


2 Answers

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

like image 132
Nick N. Avatar answered Sep 24 '22 06:09

Nick N.


You should be able to use general purpose Match assertion to verify multiple properties of the subject via a predicate

response.Should()         .Match<MyResponseObject>((x) =>              x.Property1 == "something" &&              x.Property2 == "anotherthing"         ); 
like image 29
Nkosi Avatar answered Sep 22 '22 06:09

Nkosi