适当的断言消息

本文关键字:消息 断言 | 更新日期: 2023-09-27 18:19:17

在一个测试中,我试图断言两个TextSpan列表的相等性/等价性,如下所示:

var expectedSpans = new List<TextSpan>()
    {
     new TextSpan { iStartLine = 1, iEndLine = 1, iStartIndex = 1, iEndIndex = 1}
    };
var obtainedSpans = new List<TextSpan>()
    {
     new TextSpan { iStartLine = 2, iEndLine = 2, iStartIndex = 1, iEndIndex = 1}
    };
Assert.That(obtainedSpans, Is.EqualTo(expectedSpans), "Unexpected spans found");

我得到的信息是:

Expected tags were not obtained.
  Expected is <System.Collections.Generic.List`1[Microsoft.VisualStudio.TextManager.Interop.TextSpan]> with 1 elements, actual is <System.Collections.Generic.List`1[Microsoft.VisualStudio.TextManager.Interop.TextSpan]> with 1 elements
  Values differ at index [0]
  Expected: Microsoft.VisualStudio.TextManager.Interop.TextSpan
  But was:  Microsoft.VisualStudio.TextManager.Interop.TextSpan

我怎样才能得到更详细的消息,至少显示所有的值,让我弄清楚在哪里失去了相等/等价?在等价断言的情况下,该消息也不提供信息。

适当的断言消息

您应该使用CollectionAssert.AreEqual(expectedSpans, obtainedSpan, "Unexpected spans found")来进行正确的列表相等断言。

顺便说一句:—使用"Assert.AreEquals()"代替"Assert.That(..., IsEqualTo())"-总是把期望放在断言失败的可读性之前