Skip to content

Assertion for key-value-pair #3470

Closed
@Falco20019

Description

@Falco20019

I was looking for a good way to check key-value-pairs. I know about DictionaryContainsKeyConstraint and DictionaryContainsValueConstraint, but have not found any option to combine them on the same item. Chaining it with And will also operate on the asserted value and not on the item identified by the key.

public void Merge_NoConflicts()
{
    var mainDict = new Dictionary<string, int>
    {
        { "Test", 1 }
    };
    var otherDict = new Dictionary<string, int>
    {
        { "Test2", 42 }
    };

    var result = mainDict.Merge(otherDict);

    // --- Variant 1 (full checks, ugly to read) ---
    Assert.That(result, Contains.Key("Test"));
    Assert.That(result["Test"], Is.EqualTo(1));
    Assert.That(result, Contains.Key("Test2"));
    Assert.That(result["Test2"], Is.EqualTo(42));

    // --- Variant 2 (better but throws KeyNotFoundException, would like outlike like SomeItemsConstraint) ---
    Assert.That(result["Test"], Is.EqualTo(1));
    Assert.That(result["Test2"], Is.EqualTo(42));

    // --- Variant 3 (works, better than 1 but but uglier to read than 2) ---
    Assert.That(result, Contains.Item(new KeyValuePair<string, int>("Test", 1)));
    Assert.That(result, Contains.Item(new KeyValuePair<string, int>("Test2", 42)));

    // --- Variant 4 (looks correct, but ContainValue is called on result, so no relation to the pair) ---
    Assert.That(result, Contains.Key("Test").And.ContainValue(1));
    Assert.That(result, Contains.Key("Test2").And.ContainValue(42));

    // --- Variant 5 (some API I would prefer but can't find) ---
    Assert.That(result, Contains.Key("Test").WithValue(1));
    Assert.That(result, Contains.Key("Test2").WithValue(42));
}

It would be pretty easy to implement an DictionaryContainsKeyValueConstraint that implements the Matches method using TryGet. It's also easy to add the WithValue method to DictionaryContainsKeyConstraint and have it work with all notations (Contains.Key, Does.ContainKey, ...). But before doing a PR, I wanted to know if there already is a good way of doing it and just not finding it.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions