-2

Is there an existing assert to assert 2 similar objects?

I tried using Assert.Equal but it doesn't work correctly on objects.

2 Answers2

3
public static bool IsEqual(this object obj, object another)
{
  if (ReferenceEquals(obj, another)) return true;
  if ((obj == null) || (another == null)) return false;
  if (obj.GetType() != another.GetType()) return false;

  var objJson = JsonConvert.SerializeObject(obj);
  var anotherJson = JsonConvert.SerializeObject(another);

  return objJson == anotherJson;
}
Zanyar Jalal
  • 1,407
  • 12
  • 29
2

You can compare the fields of the objects for example:

Customer actual = new Customer { Id = 1, Name = "John" };
Customer expected = new Customer { Id = 1, Name = "John" };

Assert.Equal(expected, actual); // The test will fail here

you can compare doing that:

Assert.Equal(expected.Id, actual.Id);
Assert.Equal(expected.Name, actual.Name);