How to Compare two objects in unit test?

前端 未结 15 1701
自闭症患者
自闭症患者 2020-11-30 03:15
public class Student
{
    public string Name { get; set; }
    public int ID { get; set; }
}

...

var st1 = new Student
{
    ID =          


        
15条回答
  •  清歌不尽
    2020-11-30 03:39

    If comparing public members is enough for your use-case, simply jam your objects into JSON and compare the resulting strings:

    var js = new JavaScriptSerializer();
    Assert.AreEqual(js.Serialize(st1), js.Serialize(st2));
    

    JavaScriptSerializer Class

    Pros

    • Requires minimal code, zero effort, and no preliminary setup
    • Handles complex structures with nested objects
    • Does not pollute your types with unit test-specific code, like Equals

    Cons

    • Only serializable, public members are considered (no need to annotate your members, though)
    • Does not handle circular references

提交回复
热议问题