回答

0

我觉得这是更好地重写您SomeClassEqualsGetHashCode方法比较Id和Name属性:

public class SomeClass 
{ 
    public int Id { get; set; } 
    public string Name { get; set; }  

    public override bool Equals(object obj) 
    { 
     SomeClass other = obj as SomeClass; 
     if (other == null) 
      return false; 

     return other.Id == Id && other.Name == Name; 
    } 

    // GetHashCode implementation 
} 

断言看起来像:

Assert.AreEqual(expectedObject, someClass); 

如果您不想或不能更改SomeClass实施,那么您可以创建方法,它会做断言:

public void AssertAreEqual(SomeClass expected, SomeClass actual) 
{ 
    Assert.AreEqual(expected.Id, actual.Id); 
    Assert.AreEqual(expected.Name, actual.Name); 
} 

评估调试器显示字符串不是简单的任务,因为DebuggerDisplayAttribute只包含格式字符串,它是用来评估在调试对象的字符串表示。除简单属性名称之外,该字符串还可以包含表达式和方法调用。您可以在Roslyn编译器的帮助下评估调试器显示值,如here所述。但我不认为使用调试器元数据是检查对象相等性的好方法。

+0

您会看到,它是一个具有此属性集的外部类,因此我无法对其进行修改。我不想仅仅为了测试目的而重写它。 – dbardakov

+0

OFc,我可以自己收集这些属性值,但使用我提供的伪代码不方便吗? ) – dbardakov

+0

@dbardakov从一些对象的调试器显示属性来评估格式字符串并不那么简单。 [Here](http://stackoverflow.com/questions/10942258/any-code-that-duplicates-how-the-debuggerdisplayattribute-generates-the-resultin)是使用[Roslyn](http:// msdn。 microsoft.com/en-US/roslyn)编译器。我会用一些对象比较器方法 –

相关问题