在C#测试中比较两个相似的对象
c#
是否有现有的断言来断言 2 个类似的对象?
我尝试使用,Assert.Equal但它在对象上无法正常工作。
回答
如果我理解正确,您可以使用DeepEqualNuGet 包,然后在代码中:
actualObject.ShouldDeepEqual(expectedObject);
另一种选择是使用FluentAssertionsNuGet 包,然后在代码中:
actualObject.Should().BeEquivalentTo(expectedObject);
回答
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;
}