Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c# - Fluent Assertion - compare models properties ignoring null values

case I am working on is - what is best solution to compare two objects with properties but excluding members with null values.

Ex.

objectA.prop1 = "value1";
objectA.prop2 = "value2";
objectA.prop3 = "value3";

expectedObjectB.prop1 = null;
expectedObjectB.prop2 = "value2";
expectedObjectB.prop3 = null;

objectA.Should().BeEquivalentTo(expectedObjectB);

It compares all properties one-to-one. How to make it compare only prop2 in that case and ignore other? Should I use Exclude method?

question from:https://stackoverflow.com/questions/65905153/fluent-assertion-compare-models-properties-ignoring-null-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to solve this is use an anonymous object. BeEquivalentTo looks at the expectation to decide what properties to consider when doing an structural equivalency comparison.

In this

class MyClass
{
    string Prop1 { get; set; }
    string Prop2 { get; set; }
}

var subject = new MyClass
{
    Prop1 = "IrrelevantValue",
    Prop2 = "value2"
}


var expected = new
{
    Prop2 = "value2"
}

objectA.Should().BeEquivalentTo(expected);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...