Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentAssertions: Assert Collection contains Element that "IsEquivalentTo"

I'm stuck with what I thought was an easy example. I want to assert that a collection of objects contains an object that is equivalent to a given object. like: col.ShouldContainEquivalentTo(obj)

var objectList1 = new List<SomeClass> { new SomeClass("A"), new SomeClass("B"), new SomeClass("C") };
var objectList2 = new List<SomeClass> { new SomeClass("C"), new SomeClass("B"), new SomeClass("A") };

objectList1.ShouldAllBeEquivalentTo(objectList2); //this works
objectList2.ShouldContainEquivalentTo(new SomeClass("B")); //method does not exist. How can I achieve sthg like that

I want to compare based on the objects values - just like how ShouldBeEquivalentTo and ShouldAllBeEquivalentTo work. Should not be necessary to write my own equality comparer.

BR Matthias

like image 753
Matthias Avatar asked Jun 28 '17 22:06

Matthias


2 Answers

I finally had the time to implement this feature and it is now available with version 5.6.0 of FluentAssertions.

This now works!

var objectList = new List<SomeClass> { new SomeClass("A"), new SomeClass("B"), new SomeClass("C") };
objectList.Should().ContainEquivalentOf(new SomeClass("A"));

BR Matthias

like image 64
Matthias Avatar answered Oct 04 '22 15:10

Matthias


You can use the already available functionality of framework to achieve the desired behavior

This is an ugly hack but should get the job done.

public static class FluentAssertionsEx {

    public static void ShouldContainEquivalentTo<T>(this IEnumerable<T> subject, object expectation, string because = "Expected subject to contain equivalent to provided object", params object[] becauseArgs) {
        var expectedCount = subject.Count();
        var actualCount = 0;
        try {
            foreach (var item in subject) {
                item.ShouldBeEquivalentTo(expectation);
            }
        } catch {
            actualCount++;
        }
        expectedCount.Should().NotBe(actualCount, because, becauseArgs);
    }
}
like image 43
Nkosi Avatar answered Oct 04 '22 15:10

Nkosi