如何使用Fluent Assertion比较两个随属性而变化的集合? [英] How to compare two collections that vary by properties using Fluent Assertion?
问题描述
我有从内部类Rule
创建的公共类RuleInfo
.
I have public class RuleInfo
which is created from internal class Rule
.
private static RuleInfo CreateRuleInfo(Rule r)
{
return new RuleInfo
{
RuleCode = r.RuleId,
DisplayName = r.RuleCode,
Description = r.Description,
LegacyRuleCode = null
};
}
它们的属性名称不同,因此ShouldBeEquivalentTo()
或ShouldAllBeEquivalentTo()
不起作用.
They vary in their properties names so ShouldBeEquivalentTo()
or ShouldAllBeEquivalentTo()
don't work.
现在,我正在手动/明确地比较它们:
Right now I'm comparing them manually/explicitly:
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
});
}
是否有更好,更紧凑,更不明确,更易读的方式?
Is there a better, more compact, less explicit, more readable way?
推荐答案
不幸的是,当比较不同类型时,目前尚无法指定属性之间的映射.关于它,有一个公开的问题.
Unfortunately there currently isn't a way to specify a mapping between properties when comparing different types. There is an open issue about it.
这是比较两个集合的另一种示例.
请注意,我假设==
执行值相等.
因此,如果您的所有财产都是int
和string
,那么您就可以安全使用.
Here's an example on another way to compare two collections.
Be aware that I'm assuming that ==
performs value equality.
So if all your properties are int
and string
you are home safe.
ruleInfos.Should().Equal(rules, (ruleInfo, rule) =>
ruleInfo.RuleCode == rule.RuleId
&& ruleInfo.DisplayName == rule.RuleCode
&& ruleInfo.Description == rule.Description
);
例如没有超载==
的引用类型,您将需要使用例如
For e.g. a reference type with no overload of ==
you would need to handle null values gracefully with e.g.
(PropertyA == PropertyB) || (PropertyA?.Equals(PropertyB) == true
这篇关于如何使用Fluent Assertion比较两个随属性而变化的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!