【问题标题】:How to assert all items in a collection using fluent-assertions?如何使用流利断言断言集合中的所有项目?
【发布时间】:2013-09-24 20:05:58
【问题描述】:

假设我想使用fluent-assertions 测试返回一堆以下类型的项目的方法,以确保所有项目的IsActive-flag 设置为true:

public class Item
{
    public bool IsActive { get; set; }
}

为了实现这一点,我可以简单地遍历集合并在 foreach 循环中分别声明每个项目:

var items = CreateABunchOfActiveItems();
foreach (var item in items)
{
    item.IsActive.Should().BeTrue("because I said so!");
}

但是有没有更流畅的方法来一次断言整个集合中的每个项目?

【问题讨论】:

    标签: c# unit-testing collections fluent-assertions


    【解决方案1】:

    推荐的方式是使用OnlyContain:

    items.Should().OnlyContain(x => x.IsActive, "because I said so!");
    

    这些也可以:

    items.All(x => x.IsActive).Should().BeTrue("because I said so!");
    
    items.Select(x => x.IsActive.Should().BeTrue("because I said so!"))
         .All(x => true); 
    

    请注意,最后一行 (.All(x => true)) 强制前面的 Select 为每个项目执行。

    【讨论】:

    • 值得一提的是,这两个选项并不等价:.OnlyContain 要求集合不为空,而.All().Should().BeTrue() - 不等。
    【解决方案2】:

    用 foreach 方法替换你的 foreach 循环应该可以解决问题(至少一点点)。

    var items = CreateABunchOfActiveItems();
    items.ForEach(item => item.IsActive.Should().BeTrue("because I said so, too!"));
    

    我发现这种语法比传统的 foreach 循环更流畅:)

    如果您的方法 CreateABunchOfActiveItems 返回一个 IEnumerable,则未定义 ForEach 方法。但它可以很容易地实现为扩展方法:

    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, 
        Action<T> action)
    {
        // I use ToList() to force a copy, otherwise your action 
        // coud affect your original collection of items!. If you are confortable 
        // with that, you can ommit it
        foreach (T item in enumeration.ToList())
        {
            action(item);
            yield return item;
        }
    }
    

    【讨论】:

    • 这也是一种有效的方法 - 并且有提供 ForEach-extension 的库。但我主要是在寻找是否有一种方法可以使用 fluent-assertion 库本地执行这种操作。
    • 还要注意,ToList() 已经枚举了原始集合,然后由foreach-loop 再次枚举...
    • 是的,我知道这可能不是处理繁重操作(许多项目、数据库连接、文件读取等)时的最佳方法,但它适合我的日常测试。跨度>
    猜你喜欢
    • 2021-11-21
    • 2012-02-18
    • 2020-03-16
    • 2016-10-19
    • 2021-01-08
    • 2022-07-23
    • 2022-03-23
    • 2020-02-08
    • 2014-07-27
    相关资源
    最近更新 更多