9

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
}
YMM
  • 632
  • 1
  • 10
  • 21

2 Answers2

9

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);

Update

With version 6.5.0 it is also possible to use AllSatisfy:

collection.Should().AllSatisfy(i => i.CampusId.Should().Be(38))
Stefan Golubović
  • 1,225
  • 1
  • 16
  • 21
  • Will OnlyContain assert that each element's CampusId equals 38? If yes, can I have more predicates at once? E. g. CampusId == 38 and CurrentStudentCount <= MaxStudentCount? – YMM Dec 09 '21 at 00:03
  • 2
    Yes, `OnlyContain` asserts that all elements match the predicate. `collection.Should().OnlyContain(i => i.CampusId == 38 && i.CurrentStudentCount <= i.MaxStudentCount);`. There's an open issue about having a `AllSatisfy` https://github.com/fluentassertions/fluentassertions/issues/1179 – Jonas Nyrup Dec 09 '21 at 06:48
5

Use AllSatisfy(), which was added in v. 6.5.0 as per https://fluentassertions.com/collections/.

In your case, it would be:

collection.Should().AllSatisfy(
    i => i.CampusId.Should().Be(38)
);
Grzegorz Smulko
  • 2,525
  • 1
  • 29
  • 42