Be().Equal() for Dictionary with List<> as value fails #1734
-
DescriptionIf List of items is used as a Dictionary value Equal fails when it should not. See example, it's short and obvious. Complete minimal example reproducing the issueusing System;
using System.Collections.Generic;
using FluentAssertions;
using NUnit.Framework;
namespace TestProject1
{
public class Tests
{
[Test]
public void Dictionary()
{
var r1 = new Record(typeof(IDisposable));
var r2 = new Record(typeof(IDisposable));
r1.Should().Be(r2); // passed: ensure that objects are equal
var l1 = new List<Record> { r1 };
var l2 = new List<Record> { r2 };
l1.Should().Equal(l2); // passed: ensure that List containing these objects are equal
var d1 = new Dictionary<string, List<Record>> { { "key", l1 } };
var d2 = new Dictionary<string, List<Record>> { { "key", l2 } };
d1.Should().Equal(d2); // fails with
// Expected d1 to be equal to
// {["key"] = {Type: IDisposable}}, but
// {["key"] = {Type: IDisposable}} differs at key "key".
}
}
public class Record
{
private Type type;
public Record(Type type) => this.type = type;
public override bool Equals(object obj) => Equals(obj as Record);
private bool Equals(Record other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return type == other.type;
}
public override int GetHashCode() => type.GetHashCode();
public override string ToString() => $"Type: {type.Name}";
}
} Expected behavior:Should treat dictionaries as equal. Actual behavior:Fails with the message: Versions
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is by design.
|
Beta Was this translation helpful? Give feedback.
This is by design.
Equal
on a collection will ensure all items in one collection appear in the same order as the other collection. It uses the item'sEquals
implementation for the comparison.Equal
on a dictionary will ensure that each key exists in the other dictionary and that their value match. AList<T>
is a reference type, so by definition, they will never by "equal". If you want to do a deep comparison, useBeEquivalentTo
.