【问题标题】:Satisfy() in Fluent Assertions does not work with collections of class objectsFluent Assertions 中的 Satisfy() 不适用于类对象的集合
【发布时间】:2022-01-13 20:23:18
【问题描述】:

我有一堂课:

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

以及该类的对象集合:

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

我想断言每个对象的CampusId 等于 38:

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

但断言失败并显示以下消息:

预期集合满足所有谓词,但以下元素不匹配任何谓词:

Index: 1, Element: TestClass

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

Index: 2, Element: TestClass

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

【问题讨论】:

    标签: c# assertion fluent-assertions


    【解决方案1】:

    Satisfy(和SatisfyRespectively)要求集合中的每个元素都有一个 lambda。你的情况是:

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

    另一种选择是使用OnlyContain

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

    【讨论】:

    • OnlyContain 是否会断言每个元素的 CampusId 等于 38?如果是,我可以一次拥有更多谓词吗?例如。 CampusId == 38 和 CurrentStudentCount
    • 是的,OnlyContain 断言所有元素都与谓词匹配。 collection.Should().OnlyContain(i => i.CampusId == 38 && i.CurrentStudentCount <= i.MaxStudentCount);。关于拥有AllSatisfy github.com/fluentassertions/fluentassertions/issues/1179 有一个未解决的问题
    猜你喜欢
    • 2017-07-20
    • 2017-04-15
    • 2020-07-04
    • 2022-01-03
    • 2022-06-30
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    相关资源
    最近更新 更多