DictionaryContainsKeyValuePair Constraint
DictionaryContainsKeyValuePairConstraint tests whether a dictionary contains a specific key-value pair.
Usage
Does.ContainKey(object key).WithValue(object value)
Does.Not.ContainKey(object key).WithValue(object value)
Modifiers
These modifiers apply to the value comparison:
.IgnoreCase
.IgnoreWhiteSpace // NUnit 4.2+
.Using(IComparer comparer)
.Using(IEqualityComparer comparer)
.Using<T>(IComparer<T> comparer)
.Using<T>(IEqualityComparer<T> comparer)
.Using<T>(Comparison<T> comparer)
.Using<T>(Func<T, T, bool> comparer)
.UsingPropertiesComparer() // NUnit 4.1+
Examples
[Test]
public void DictionaryContainsKeyValuePairConstraint_Examples()
{
var translations = new Dictionary<string, string>
{
["Hello"] = "World",
["Hola"] = "Mundo"
};
// Check for specific key-value pair
Assert.That(translations, Does.ContainKey("Hello").WithValue("World"));
Assert.That(translations, Does.ContainKey("Hola").WithValue("Mundo"));
// Negative: key exists but value doesn't match
Assert.That(translations, Does.Not.ContainKey("Hello").WithValue("Universe"));
// Case-insensitive value comparison
Assert.That(translations, Does.ContainKey("Hello").WithValue("WORLD").IgnoreCase);
}
Notes
- Key comparison uses the dictionary's comparer (cannot be overridden).
- Value comparison modifiers (
.IgnoreCase,.Using(), etc.) only apply to the value. - The preferred syntax is
Does.ContainKey(key).WithValue(value)rather than the constructor form.