假设我想使用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!");
}但是,有没有一种更流畅的方法来一次断言整个集合中的每一项?
发布于 2013-09-20 00:09:58
推荐的方法是使用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。
发布于 2013-09-20 00:39:17
像用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;
}
}https://stackoverflow.com/questions/18899755
复制相似问题