DictionaryContainsKey Constraint
DictionaryContainsKeyConstraint tests whether a dictionary contains an expected key.
Usage
Contains.Key(object expectedKey)
Does.ContainKey(object expectedKey)
Does.Not.ContainKey(object expectedKey)
Modifiers
.WithValue(object expectedValue) // Also check the corresponding value
Examples
[Test]
public void DictionaryContainsKeyConstraint_Examples()
{
var dictionary = new Dictionary<string, int>
{
["Alice"] = 30,
["Bob"] = 25
};
// Basic key checks
Assert.That(dictionary, Contains.Key("Alice"));
Assert.That(dictionary, Does.ContainKey("Bob"));
Assert.That(dictionary, Does.Not.ContainKey("Carol"));
// Check key with corresponding value
Assert.That(dictionary, Does.ContainKey("Alice").WithValue(30));
Assert.That(dictionary, Does.ContainKey("Bob").WithValue(25));
}
Dictionary Comparer Behavior
Key comparison uses the dictionary's own comparer:
[Test]
public void DictionaryContainsKey_Comparer_Examples()
{
// Case-sensitive dictionary (default)
var caseSensitive = new Dictionary<string, string> { ["Hello"] = "World" };
Assert.That(caseSensitive, Does.ContainKey("Hello"));
Assert.That(caseSensitive, Does.Not.ContainKey("hello")); // Different case
// Case-insensitive dictionary
var caseInsensitive = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["Hello"] = "World"
};
Assert.That(caseInsensitive, Does.ContainKey("Hello"));
Assert.That(caseInsensitive, Does.ContainKey("hello")); // Same due to comparer
// Note: .IgnoreCase on WithValue applies to the VALUE, not the key
Assert.That(caseInsensitive, Does.ContainKey("hello").WithValue("world").IgnoreCase);
}
Notes
- Key comparison always uses the dictionary's comparer, not NUnit's modifiers.
- The
.WithValue()modifier converts this to a key-value pair check. - As of NUnit 4.4, comparison modifiers on keys were removed as they were non-functional.