在FluentAssertions中的自定义断言中重用内置对象图比较

时间:2019-12-15 23:32:33

标签: c# testing fluent-assertions

如何在我的object graph comparison类中重用FluentAssertions的内置custom assertions,以便可以使用options参数来确定比较范围。

这里是一个例子。有一个称为记录的基本实体,它可以表示其他几个实体。接下来是它代表的实体。

public class Record
{
    public long No;
    public string Version;
    public string Type;
    public string[] Fields = new string[10];
}

public class Projection
{
    private readonly Record _Record;
    public Projection(Record record)
    {
        _Record = record;
    }
    public String Field1 => _Record.Fields[2];
    public String Field2 => _Record.Fields[5];
    public String Field3 => _Record.Fields[8];
    public static readonly EmptyFields = new array[] { 0, 1, 3, 4, 6, 7, 9 };
}

我为Projection类创建了一个自定义断言类

public class ProjectionAssertions : ReferenceTypeAssertions<Projection, ProjectionAssertions>
{
    protected override string Identifier => "Projection";

    public ProjectionAssertions(Projection instance)
    {
        Subject = instance;
    }

    public AndConstraint<ProjectionAssertions> BeProjection(
        string because = "",
        params object[] becauseArgs)
    {
        Subject.Type.Should().Be("PRJ", because, becauseArgs);

        return new AndConstraint<ProjectionAssertions>(this);
    }

    public AndConstraint<ProjectionAssertions> BeEquivalentTo(
        ProjectionFields expected,
        string because = "",
        params object[] becauseArgs)
    {
        Execute.Assertion.
            BecauseOf(because, becauseArgs).
            ForCondition(expected != null).
            FailWith("'expected' should not be null.").
            Then.
            Given(() => Subject).
                ForCondition(s => s.Field1 == expected.Field1).
                FailWith("message1").
            Then.
                ForCondition(s => s.Field2 == expected.Field2).
                FailWith("message2").
            Then.
                ForCondition(s => s.Field3 == expected.Field3).
                FailWith("message3");

        return new AndConstraint<ProjectionAssertions>(this);
    }
}

但是我想在自定义BeEquivalentTo方法中执行以下操作:

var fieldsToCheck = List<string>() { "Version", "Type" };
record.Should().
    BeEquivalentTo(
        expectedRecord,
        options => options.Including(ctx => fieldsToCheck.Contains(ctx.SelectedMemberPath)))

我该如何实现?

0 个答案:

没有答案