Compare equality between two objects in NUnit

Do not override Equals just for testing purposes. It’s tedious and affects domain logic.
Instead,

Use JSON to compare the object’s data

No additional logic on your objects. No extra tasks for testing.

Just use this simple method:

public static void AreEqualByJson(object expected, object actual)
{
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var expectedJson = serializer.Serialize(expected);
    var actualJson = serializer.Serialize(actual);
    Assert.AreEqual(expectedJson, actualJson);
}

It seems to work out great. The test runner results info will show the JSON string comparison (the object graph) included so you see directly what’s wrong.

Also note! If you have bigger complex objects and just want to compare parts of them you can (use LINQ for sequence data) create anonymous objects to use with above method.

public void SomeTest()
{
    var expect = new { PropA = 12, PropB = 14 };
    var sut = loc.Resolve<SomeSvc>();
    var bigObjectResult = sut.Execute(); // This will return a big object with loads of properties 
    AssExt.AreEqualByJson(expect, new { bigObjectResult.PropA, bigObjectResult.PropB });
}

Leave a Comment