FluentAssertions: check a list contains an object, excluding a property

Darren Hall picture Darren Hall · Mar 28, 2017 · Viewed 7.5k times · Source

I have several Event classes which implement IEvent. To check actual event against expected event I use

actualEvent.ShouldBeEquivalentTo(expectedEvent,opt => opt.RespectingRuntimeTypes()
                                                         .Excluding(e => e.DateCreated));

The events have a DateCreated property which I ignore as the actual and expected are created at different times.

How do I check if expectedEvent exists at least once in a list of actualEvents?

I would like to do the following;

actualEvents.Should().Contain(expectedEvent,opt => opt.RespectingRuntimeTypes()
                                                      .Excluding(e => e.DateCreated));

but it is not possible.

Can this be done in fluentassertions?

Answer

Trevor picture Trevor · Apr 3, 2017

I had a similar scenario where I had a list of items (an object with properties) and I wanted to check if the list contained a local item I was testing for.

I found the solution on this question: FluentAssertions, making sure IEnumerable contains only single element

I simplified my solution by writing the following statement:

FooList.Should().Contain(fooItem, x => true)

The above constraint states the FooList object should contain the fooItem this is expressed with the lambda x => true.

Fairly straight forward and worked for my use case. Give it a try and check out that question thread I linked it may help.

Good luck.