c# - Comparing similar objects in Unit Tests -


what best way compare 2 similar objects?

given flintlockdto , flintlock:

public class flintlockdto {   public string gname { get; set; }    public string sharedpropertyname { get; set; }    ... } 

and

public class flintlock {   public flintlock(flintlockdto inflator)   {     this.goodname = inflator.gname;     this.sharedpropertyname = inflator.sharedpropertyname;     ...   }    public string goodname { get; private set; }    public string sharedpropertyname { get; private set; }   ... } 

where both classes share n properties (e.g. sharedpropertyname), differ on m properties equivalent, named differently (e.g. goodname \ gname.)

tools such fluentassert this, if property names matched, understanding work:

flintlockdto.shouldbeequivalentto(flintlock); 

is there way neatly in fluentassert or other tool?

ideally,

flintlockdto.isthesameas(flintlock).whenmapping("gname","goodname"); 

i decided elaborate more likeness mentioned striplingwarrior. it's available nuget package.

here example:

using nunit.framework; using ploeh.semanticcomparison; using ploeh.semanticcomparison.fluent;  namespace tests {     [testfixture]     class tests2     {         [test]         public void objectsshuldequal()         {             var flintlockdto = new flintlockdto()             {                 gname = "name",                 additionalproperty = "whatever",                 sharedpropertyname = "prop name"             };             var flintlock = new flintlock(flintlockdto);              likeness<flintlock, flintlockdto> flintflockdtolikeness = flintlock                 .assource().oflikeness<flintlockdto>()                 .with(dto => dto.gname).equalswhen((flintlock1, dto) => flintlock1.goodname == dto.gname) // can write extension method encapsulate                 .without(dto => dto.additionalproperty);              // assert             flintflockdtolikeness.shouldequal(flintlockdto);         }     }      public class flintlockdto     {         public string gname { get; set; }          public string sharedpropertyname { get; set; }          public string additionalproperty { get; set; }     }      public class flintlock     {         public flintlock(flintlockdto inflator)         {             this.goodname = inflator.gname;             this.sharedpropertyname = inflator.sharedpropertyname;         }          public string goodname { get; private set; }          public string sharedpropertyname { get; private set; }     } } 

as can see:

  • it performs auto comparison on properties same names
  • you can specify if properties of different names should match (this 1 pretty ugly out of box, can write extension method encapsulate it)
  • you can specify if property should not compared

Comments