Skip to main content
 首页 » 编程设计

c#之存在差异时如何让 NUnit 集合比较调用 ToString

2024年02月03日26me-sa

我正在使用 VS 2010,并使用 NUnit 运行我的单元测试。以下行正确检测两个列表是否不同:

        CollectionAssert.AreEqual(expected, actual); 

但是,我想要一个比以下更好的错误消息:

Expected and actual are both <System.Collections.Generic.List`1[MyNamespace.MyClass]> with 2 elements 
  Values differ at index [0] 
  Expected: <MyNamespace.MyClass> 
  But was:  <MyNamespace.MyClass> 

在 MyNamespace.MyClass 中,我实现了以下方法:

public new string ToString() 

我希望 NUnit 输出以下内容:

Expected and actual are both <System.Collections.Generic.List`1[MyNamespace.MyClass]> with 2 elements 
  Values differ at index [0] 
  Expected: <24 ounces of cold beer> 
  But was:  <2.4 ounces of rotten tomatoes> 

但是,NUnit 不会调用它。我错过了什么?

请您参考如下方法:

您已经隐藏 object 的方法而不是覆盖它。使用这个:

public override string ToString() 

基本上 NUnit 只是调用 object.ToString() - 您没有覆盖它。除非它专门寻找一个带有反射的新方法,否则它不会找到您的方法 - 覆盖是执行此操作的惯用方法。这只是一个简单的错误,还是您有意出于某种原因隐藏该方法?