在 C# 测试中比较两个相似的对象

Tay*_*sso 3 c#

是否有现有的断言来断言 2 个类似的对象?

我尝试使用,Assert.Equal但它在对象上无法正常工作。

Mis*_*sky 14

如果我理解正确,您可以使用DeepEqualNuGet 包,然后在代码中:

actualObject.ShouldDeepEqual(expectedObject);
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用FluentAssertionsNuGet 包,然后在代码中:

actualObject.Should().BeEquivalentTo(expectedObject);
Run Code Online (Sandbox Code Playgroud)


Zan*_*lal 6

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;
}
Run Code Online (Sandbox Code Playgroud)