Satisfy() in Fluent Assertions does not work with collections of class objects

Viewed 1259

I have a class:

public class TestClass
{
    public int Id { get; set; }
    
    public int CampusId { get; set; }
    
    public int CurrentStudentCount { get; set; }
    
    public int MaxStudentCount { get; set; }
}

and a collection of objects of this class:

var collection = new[]
    {
        new TestClass
        {
            Id = 55,
            CampusId = 38,
            CurrentStudentCount = 1,
            MaxStudentCount = 2
        },
        new TestClass
        {
            Id = 127,
            CampusId = 38,
            CurrentStudentCount = 2,
            MaxStudentCount = 2
        },
        new TestClass
        {
            Id = 126,
            CampusId = 38,
            CurrentStudentCount = 2,
            MaxStudentCount = 2
        }
    };

I'd like to assert that each object's CampusId equals 38:

collection.Should().Satisfy(i => i.CampusId == 38);

But the assertion fails with the following message:

Expected collection to satisfy all predicates, but the following elements did not match any predicate:

Index: 1, Element: TestClass

{
    CampusId = 38, 
    CurrentStudentCount = 2, 
    Id = 127, 
    MaxStudentCount = 2
}

Index: 2, Element: TestClass

{
    CampusId = 38, 
    CurrentStudentCount = 2, 
    Id = 126, 
    MaxStudentCount = 2
}
2 Answers

Satisfy (and SatisfyRespectively) requires a lambda for each element in a collection. In your case that would be:

collection.Should().Satisfy(
    i => i.CampusId == 38,
    i => i.CampusId == 38,
    i => i.CampusId == 38
);

The other option would be to use OnlyContain:

collection.Should().OnlyContain(i => i.CampusId == 38);
Related