Search Results for

    Show / Hide Table of Contents

    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

    1. Key comparison uses the dictionary's comparer (cannot be overridden).
    2. Value comparison modifiers (.IgnoreCase, .Using(), etc.) only apply to the value.
    3. The preferred syntax is Does.ContainKey(key).WithValue(value) rather than the constructor form.

    See Also

    • DictionaryContainsKey Constraint
    • DictionaryContainsValue Constraint
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0