如何动态地 select 属性进行等效性测试 - FluentAssertions

How can I dynamically select properties for equivalency test - FluentAssertions

我正在创建单元测试,我将在其中比较对象列表。

目前我正在结合 specflow 和 nunit 使用 Fluent 断言。我已经使用 Fluent Assertions 做了如下比较:

public void TestShizzle()
{
    // I normally retrieve these lists from a moq database or a specflow table
    var expected = list<myObject> 
    {
        new myObject 
        {
            A = 1,
            B = "abc"
        }
    }

    var found = list<myObject> 
    {
        new myObject 
        {
            A = 1,
            B = "def"
        }
    }

    // this comparison only compares a few columns. The comparison is also object dependent. I would like to make this dynamic
    found.Should().BeEquivalentTo(
        expected,
        options =>
        options.Including(x => x.A));
}

我真正想要的是能够使用泛型而不是指定类型。我还想决定在编译时比较哪些属性。这是因为数据库中有大量的表。我想我需要为此使用 Linq 表达式,但我不知道该怎么做。该函数应如下所示:

public void GenericShizzle<T>(List<T> expected, List<T> found, IEnumerable<PropertyInfo> properties)
{
    Expression<Func<T, object>> principal;
    foreach(var property in properties)
    {
        // create the expression for including fields
    }

    found.Should().BeEquivalentTo(
        expected,
        options =>
        // here is need to apply the expression.
}

我真的不知道如何为工作获得正确的表达方式,或者这是否是最好的方法。我想我需要创建一个包含函数可以理解的 属性 表达式,但也许可以使用不同的方法?

Including 方法重载接受 Expression<Func<IMemberInfo, bool>> 可用于根据有关成员的信息动态过滤成员:

IEnumerable<PropertyInfo> properties = ...;
var names = properties
    .Select(info => info.Name)
    .ToHashSet();
found.Should()
    .BeEquivalentTo(expected,
         options => options.Including((IMemberInfo mi) => names.Contains(mi.Name))); // or just .Including(mi => names.Contains(mi.Name))