在CollectionAssert中AssertFailedException.AreEquivalent(两个列表都包

本文关键字:两个 列表 CollectionAssert AssertFailedException AreEquivalent | 更新日期: 2023-09-27 18:16:33

我得到以下AssertFailedException,不能看到,为什么会发生这种情况。

CollectionAssert。AreEquivalent失败了。预期的集合包含1个实际的集合包含0个事件

代码:

[TestMethod]
public void GetDocumentsTest()
{
    List<Document> testDocuments = new List<Document>() {
      new Document(){ Path = "TestDoc1", Language = "DEU" }
    , new Document(){ Path = "TestDoc2", Language = "ENG" }
    };
    string sqlCommand = "SELECT Path, LanguageCode FROM Document WITH(NOLOCK) ORDER BY Id";
    string connectionString = "Data Source=|DataDirectory|''Documents.sdf;Persist Security Info=False;";
    List<Document> documents = new DataAccessManagerTestMockup().GetDocuments(sqlCommand, connectionString);
// Sql gets same documents with same path and same language
    CollectionAssert.AreEquivalent(testDocuments, documents);
}
更新:

namespace FileExporter
{
    public class Document
    {
        public string Path { get; set; }
        public string Language { get; set; }
        public bool Equals(Document y)
        {
            if (object.ReferenceEquals(this, y))
                return true;
            if (object.ReferenceEquals(this, null) || object.ReferenceEquals(y, null))
                return false;
            return this.Path == y.Path && this.Language == y.Language;
        }
    }
}
更新2:

我认为我不应该花一个晚上在科隆(3小时的车程),并试图编码。同事刚才说我应该重写等号,用一个对象代替Document。

namespace FileExporter
{
    public class Document
    {
        public string Path { get; set; }
        public string Language { get; set; }
        public override bool Equals(object y)
        {
            if (object.ReferenceEquals(this, y))
                return true;
            if (object.ReferenceEquals(this, null) || object.ReferenceEquals(y, null))
                return false;
            return this.Path == ((Document) y).Path && this.Language == ((Document) y).Language;
        }
        public override int GetHashCode()
        {
        if (this == null)
            return 0;
        int hashCodePath = this.Path == null ? 0 : this.Path.GetHashCode();
        int hashCodeLanguage = this.Language == null ? 0 : this.Language.GetHashCode();
        return hashCodePath ^ hashCodeLanguage;
        }
}

在CollectionAssert中AssertFailedException.AreEquivalent(两个列表都包

要做到这一点,您的文档类需要实现(覆盖)Equals()

您可以很容易地验证:

var d1 = new Document(){ Path = "TestDoc1", Language = "DEU" };
var d2 = new Document(){ Path = "TestDoc1", Language = "DEU" };
Assert.AreEqual(d1, d2);