Skip to content

Commit e00537e

Browse files
authored
Fix KeyNotFoundException when comparing dictionaries (#2351)
1 parent bc068b5 commit e00537e

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

TUnit.Assertions.UnitTests/DictionaryAssertionTests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Collections.Immutable;
12
using TUnit.Assertions.Extensions;
23

34
namespace TUnit.Assertions.UnitTests;
@@ -36,4 +37,13 @@ public async Task String_Dictionary_Contains_Key_IgnoreCase()
3637

3738
await TUnitAssert.That(dictionary).ContainsKey("blah", StringComparer.InvariantCultureIgnoreCase);
3839
}
40+
41+
[Test]
42+
public async Task Immutable_Dictionary_Does_Not_Contain_Key()
43+
{
44+
await TUnitAssert.ThrowsAsync<TUnitAssertionException>(async () =>
45+
await TUnitAssert.That(ImmutableDictionary<string, int>.Empty.Add("Hello", 1))
46+
.IsEquivalentTo(ImmutableDictionary<string, int>.Empty.Add("Hello2", 1))
47+
);
48+
}
3949
}

TUnit.Assertions/Compare.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,32 @@ private static IEnumerable<ComparisonFailure> CheckEquivalent<
9191

9292
foreach (var key in keys)
9393
{
94+
if (!actualDictionary.Contains(key))
95+
{
96+
yield return new ComparisonFailure
97+
{
98+
Type = MemberType.DictionaryItem,
99+
Actual = $"No entry with key: {key}",
100+
Expected = $"[{key}] = {expectedDictionary[key]}",
101+
NestedMemberNames = [..memberNames, $"[{key}]"]
102+
};
103+
104+
yield break;
105+
}
106+
107+
if (!expectedDictionary.Contains(key))
108+
{
109+
yield return new ComparisonFailure
110+
{
111+
Type = MemberType.DictionaryItem,
112+
Actual = $"[{key}] = {actualDictionary[key]}",
113+
Expected = $"No entry with key: {key}",
114+
NestedMemberNames = [..memberNames, $"[{key}]"]
115+
};
116+
117+
yield break;
118+
}
119+
94120
var actualObject = actualDictionary[key];
95121
var expectedObject = expectedDictionary[key];
96122

0 commit comments

Comments
 (0)