我有几个实现IEvent的事件类。要根据我使用的预期事件检查实际事件
actualEvent.ShouldBeEquivalentTo(expectedEvent,opt => opt.RespectingRuntimeTypes()
.Excluding(e => e.DateCreated));
这些事件有一个 DateCreated 属性,我忽略了该属性,因为实际和预期是在不同的时间创建的。
如何检查预期事件在实际事件列表中是否至少存在一次?
我想做以下几点;
actualEvents.Should().Contain(expectedEvent,opt => opt.RespectingRuntimeTypes()
.Excluding(e => e.DateCreated));
但这是不可能的。
这可以在流利的断言中完成吗?
我有一个类似的场景,我有一个项目列表(一个具有属性的对象(,我想检查该列表是否包含我正在测试的本地项目。
我找到了这个问题的解决方案:FluentAssertions,确保IEnumerable只包含单个元素
我通过编写以下语句简化了我的解决方案:
FooList.Should().Contain(fooItem, x => true)
上面的约束声明 FooList 对象应包含 fooItem 这用 lambda x => true 表示。
相当简单明了,适用于我的用例。试一试,看看我链接的问题线程可能会有所帮助。
祝你好运。
使用 FluentAssertions 4.19.4,我通过实现自己的扩展方法解决了这个问题。
集合中的每个元素都针对预期的元素单独断言,使用 ShouldBeEquivalentTo 方法,该方法可以接受配置参数。
using FluentAssertions.Collections;
using FluentAssertions.Equivalency;
using FluentAssertions.Execution;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace FluentAssertions.Extensions
{
public static class FluentAssertionsHelper
{
public static AndWhichConstraint<TAssertions, T> Contain<TAssertions, T>(this SelfReferencingCollectionAssertions<T, TAssertions> colAssert,
T expected,
Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config,
string because = "",
params object[] becauseArgs) where TAssertions : SelfReferencingCollectionAssertions<T, TAssertions>
{
var items = colAssert.Subject;
if (items == null)
{
Execute.Assertion.BecauseOf(because, becauseArgs).FailWith("Expected {context:collection} to contain {0}{reason}, but found {1}.", expected, items);
}
var containsItem = false;
using (var scope = new AssertionScope())
{
foreach (var item in items)
{
try
{
item.ShouldBeEquivalentTo(expected, config, because, becauseArgs);
}
catch (NullReferenceException) { }
var failures = scope.Discard();
if (!failures.Any())
{
containsItem = true;
break;
}
}
}
if (!containsItem)
{
Execute.Assertion.BecauseOf(because, becauseArgs).FailWith("Expected {context:collection} {0} to contain {1}{reason}.", items, expected);
}
return new AndWhichConstraint<TAssertions, T>((TAssertions)colAssert, items.Where(item => EqualityComparer<T>.Default.Equals(item, expected)));
}
}
}
然后,您可以编写以下内容:
using FluentAssertions;
using FluentAssertions.Extensions;
collection.Should().Contain(item, config => config.Excluding(item => item.MyProperty));