简体   繁体   中英

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

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM