包含带有谓词的属性时的异常

Exception when including properties with predicate

我正在尝试比较具有多个属性的两个对象,但需要使用谓词比较特定属性(object1object2 处没有这些属性的确切值,所以我需要在那里比较部分字符串)。

所以,我正在尝试:

object1.Should().BeEquivalentTo(object2, options => options
    .Including(o => o.Property1.StartsWith("something"))
    .Including(o => o.Property2.StartsWith("something else")
);

我希望所有其他属性都像往常一样进行比较。

但是,运行上面的代码抛出异常:

Message: System.ArgumentException : Expression <Convert(o.Property1.StartsWith("something"), Object)> cannot be used to select a member. Parameter name: expression

我查看了文档,它与我的示例相同(第 "Selecting Members" 章,位于 https://fluentassertions.com/objectgraphs/)。

为什么会出现这个异常,我该如何解决?

Why does this exception occur

异常发生是因为你正在调用一个函数

.Including(o => o.Property1.StartsWith("something")) //<-- expects property only

在一个只希望得到 属性 表达式的表达式中。

.Including(o => o.Property1) //<-- expects property only

引用原始问题中链接的相同文档,您的示例在进行比较时将仅包含指定的成员。

对于您要尝试执行的操作,您应该查看 Equivalency Comparison Behavior 部分,根据您的评论,该部分可能类似于以下示例

[TestClass]
public class ObjectEquivalencyTests {
    [TestMethod]
    public void ShouldBeEquivalent() {

        var expected = new MyObject {
            Property1 = "https://www.google.com",
            Property2 = "something else"
        };

        var actual = new MyObject {
            Property1 = "https://www.google.com/search?q=test",
            Property2 = "something else"
        };

        actual.Should().BeEquivalentTo(expected, options => options
            .Using<string>(ctx => ctx.Subject.Should().StartWith(ctx.Expectation))
            .When(info => info.SelectedMemberPath == "Property1")
        );
    }
}

public class MyObject {
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}