忽略ShouldBeEquivalentTo中的内部属性 [英] Ignore internal properties in ShouldBeEquivalentTo
问题描述
在执行ShouldBeEquivalentTo时是否可以忽略类的内部属性?
Is there a way to ignore internal properties of a class when doing ShouldBeEquivalentTo?
例如,在下面的类中,我想从对象图比较中排除MetaData属性.
For example, in the class below I want to exclude the MetaData property from the object graph comparison.
public class SomeObject
{
Public string SomeString { get; set; }
internal MetaData MetaData { get; set; }
}
我宁愿不使用
someObject.ShouldBeEquivalentTo(someOtherObject, options =>
options.Excluding(info => info.SelectedMemberPath == "MetaData")
因为我可能拥有多个内部属性,所以为所有这些属性设置该属性将很繁琐.
Because I might have more than 1 internal property and setting up this for all those properties would be tedious.
推荐答案
有 IMemberSelectionRule
接口:
表示一个规则,该规则定义了在比较两个对象以确保结构相等时要包括的被测对象的成员.
Represents a rule that defines which members of the subject-under-test to include while comparing two objects for structural equality.
Implementing this interface allows to exclude all the internal properties at once (where IsAssembly
property is true
):
internal class AllExceptNonPublicPropertiesSelectionRule : IMemberSelectionRule
{
public bool IncludesMembers
{
get { return false; }
}
public IEnumerable<SelectedMemberInfo> SelectMembers(
IEnumerable<SelectedMemberInfo> selectedMembers,
ISubjectInfo context,
IEquivalencyAssertionOptions config)
{
return selectedMembers.Except(
config.GetSubjectType(context)
.GetNonPrivateProperties()
.Where(p => p.GetMethod.IsAssembly)
.Select(SelectedMemberInfo.Create));
}
}
现在该规则可用于单元测试:
Now the rule can be utilized in unit tests:
someObject.ShouldBeEquivalentTo(someOtherObject, options => options.Using(
new AllExceptNonPublicPropertiesSelectionRule()));
这篇关于忽略ShouldBeEquivalentTo中的内部属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!