如何使用Fluent Assertion比较两个因属性而异的集合?

时间:2017-12-22 19:29:50

标签: c# unit-testing fluent-assertions

我有公共课RuleInfo,它是从内部课程Rule创建的。

private static RuleInfo CreateRuleInfo(Rule r)
{
    return new RuleInfo
    {
        RuleCode = r.RuleId,
        DisplayName = r.RuleCode,
        Description = r.Description,
        LegacyRuleCode = null
    };
}

它们的属性名称各不相同,因此ShouldBeEquivalentTo()ShouldAllBeEquivalentTo()不起作用。

现在我正在手动/明确地比较它们:

foreach (var x in Enumerable.Zip(infs, rules, (i, r) => new { Info = i, Rule = r }))
{
    x.Info.ShouldBeEquivalentTo(
        new
        {
            RuleCode = x.Rule.RuleId,
            DisplayName = x.Rule.RuleCode,
            Description = x.Rule.Description,
            LegacyRuleCode = (string)null
        });
}

是否有更好,更紧凑,更不明确,更易读的方式?

2 个答案:

答案 0 :(得分:3)

一种选择是为全局选项配置添加自定义等效步骤:

class DifferentObjectsEquivalencyStep<T1, T2> : IEquivalencyStep {
    private readonly Func<T1, T2> _converter;

    public DifferentObjectsEquivalencyStep(Func<T1, T2> converter) {
        _converter = converter;
    }

    public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config) {
        return context.Subject is T1 && context.Expectation is T2 || context.Subject is T2 && context.Expectation is T1;
    }

    public bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) {            
        var first = context.Subject is T1 ? (T1) context.Subject : (T1) context.Expectation;
        var second = context.Subject is T2 ? (T2) context.Subject : (T2) context.Expectation;
        second.ShouldBeEquivalentTo(_converter(first));
        return true;
    }
}

然后在你进行所有比较之前的某个地方:

AssertionOptions.AssertEquivalencyUsing(c => c.Using(
            new DifferentObjectsEquivalencyStep<Rule, RuleInfo>(CreateRuleInfo)));

之后,常规ShouldBeEquivalentTo(和ShouldAllBeEquivalentTo)将起作用:

rule.ShouldBeEquivalentTo(info);

答案 1 :(得分:2)

不幸的是,目前还没有一种方法可以在比较不同类型时指定属性之间的映射。关于它有一个开放的issue

以下是另一种比较两个集合的方法的示例。 请注意,我假设==执行值相等。 因此,如果您的所有属性都是intstring,那么您就安全了。

ruleInfos.Should().Equal(rules, (ruleInfo, rule) =>
    ruleInfo.RuleCode == rule.RuleId
     && ruleInfo.DisplayName == rule.RuleCode
    && ruleInfo.Description == rule.Description
);

例如如果没有==重载的引用类型,则需要使用例如

优雅地处理空值
(PropertyA == PropertyB) || (PropertyA?.Equals(PropertyB) == true