<PackageReference Include="NUnit" Version="4.3.2" />

DictionaryContainsKeyValuePairConstraint

DictionaryContainsKeyValuePairConstraint is used to test whether a dictionary contains an expected object as a key-value-pair.
using NUnit.Framework.Internal; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace NUnit.Framework.Constraints { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public sealed class DictionaryContainsKeyValuePairConstraint : CollectionItemsEqualConstraint { private readonly DictionaryEntry _expected; public override string DisplayName => "ContainsKeyValuePair"; public override string Description => "dictionary containing entry " + MsgUtils.FormatValue(_expected); public DictionaryContainsKeyValuePairConstraint(object key, [System.Runtime.CompilerServices.Nullable(2)] object value) { _expected = new DictionaryEntry(key, value); } [System.Runtime.CompilerServices.NullableContext(2)] private bool Matches(object actual) { if (actual == null) throw new ArgumentException("Expected: IDictionary or IEnumerable<KeyValuePair<,>> But was: null", "actual"); if (TypeHelper.TryCast(actual, out IDictionary value)) { IDictionaryEnumerator enumerator = value.GetEnumerator(); try { while (enumerator.MoveNext()) { object current = enumerator.Current; if (ItemsEqual(current, _expected)) return true; } } finally { (enumerator as IDisposable)?.Dispose(); } return false; } if (<Matches>g__ImplementsIEnumerableKeyValuePair|6_0(actual)) { DictionaryEntry expected = _expected; object key = expected.Key; expected = _expected; KeyValuePair<object, object> keyValuePair = new KeyValuePair<object, object>(key, expected.Value); IEnumerable enumerable = (IEnumerable)actual; foreach (object item in enumerable) { if (ItemsEqual(item, keyValuePair)) return true; } return false; } DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(63, 1); defaultInterpolatedStringHandler.AppendLiteral("Expected: IDictionary or IEnumerable<KeyValuePair<,>> But was: "); defaultInterpolatedStringHandler.AppendFormatted(actual.GetType()); throw new ArgumentException(defaultInterpolatedStringHandler.ToStringAndClear(), "actual"); } public override ConstraintResult ApplyTo<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual) { return new ConstraintResult(this, actual, Matches(actual)); } protected override bool Matches(IEnumerable collection) { return Matches(collection); } } }