Using FluentAssertions 4.19.4, I solved the problem by implementing my own extension method.
Each element in the collection is asserted individually against the expected element, using the ShouldBeEquivalentTo method which can accept the config argument.
using FluentAssertions.Collections;
using FluentAssertions.Equivalency;
using FluentAssertions.Execution;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace FluentAssertions.Extensions
{
public static class FluentAssertionsHelper
{
public static AndWhichConstraint<TAssertions, T> Contain<TAssertions, T>(this SelfReferencingCollectionAssertions<T, TAssertions> colAssert,
T expected,
Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config,
string because = "",
params object[] becauseArgs) where TAssertions : SelfReferencingCollectionAssertions<T, TAssertions>
{
var items = colAssert.Subject;
if (items == null)
{
Execute.Assertion.BecauseOf(because, becauseArgs).FailWith("Expected {context:collection} to contain {0}{reason}, but found {1}.", expected, items);
}
var containsItem = false;
using (var scope = new AssertionScope())
{
foreach (var item in items)
{
try
{
item.ShouldBeEquivalentTo(expected, config, because, becauseArgs);
}
catch (NullReferenceException) { }
var failures = scope.Discard();
if (!failures.Any())
{
containsItem = true;
break;
}
}
}
if (!containsItem)
{
Execute.Assertion.BecauseOf(because, becauseArgs).FailWith("Expected {context:collection} {0} to contain {1}{reason}.", items, expected);
}
return new AndWhichConstraint<TAssertions, T>((TAssertions)colAssert, items.Where(item => EqualityComparer<T>.Default.Equals(item, expected)));
}
}
}
You can then write the following:
using FluentAssertions;
using FluentAssertions.Extensions;
collection.Should().Contain(item, config => config.Excluding(item => item.MyProperty));