我得到AssertFailedException,但看不到,为什么会这样。
CollectionAssert.AreEquivalent失败。预期的收藏 包含1次< FileExporter.Document>的出现次数。实际上 集合包含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小时)过夜并尝试编码。 同事刚刚说我应该重写equals并使用一个对象而不是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;
}
}
答案 0 :(得分:1)
为了使此成功,您的Document类需要实现(覆盖)Equals()
您可以轻松验证:
var d1 = new Document(){ Path = "TestDoc1", Language = "DEU" };
var d2 = new Document(){ Path = "TestDoc1", Language = "DEU" };
Assert.AreEqual(d1, d2);