Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Assert Dictionaries in Unit Testing

Do you know how I can Assert two dictionaries of type

Dictionary<string,List<string>>

in my Unit test project?

I tried with CollectionsAssert but it didn' work for me.I guess that it takes to simple Dictionaries as parameters(e.g. Dictionary<string,string>).I guess that the problem for me comes from the second parameter of the dictionary.Do you know how I can assert those two dictionaries?

like image 478
mathinvalidnik Avatar asked Jul 11 '13 11:07

mathinvalidnik


People also ask

How do you assert a dictionary?

to state with assurance, confidence, or force; state strongly or positively; affirm; aver: He asserted his innocence of the crime. to maintain or defend (claims, rights, etc.). to state as having existence; affirm; postulate: to assert a first cause as necessary.

What is assert unit test?

Assertions replace us humans in checking that the software does what it should. They express the requirements that the unit under test is expected to meet. Assert the exact desired behavior; avoid overly precise or overly loose conditions.

What is assert in C# unit test?

The Assert section verifies that the action of the method under test behaves as expected. For . NET, methods in the Assert class are often used for verification.


2 Answers

One of the ways that would give you a good error message:

public string ToAssertableString(IDictionary<string,List<string>> dictionary) {
    var pairStrings = dictionary.OrderBy(p => p.Key)
                                .Select(p => p.Key + ": " + string.Join(", ", p.Value));
    return string.Join("; ", pairStrings);
}

// ...
Assert.AreEqual(ToAssertableString(dictionary1), ToAssertableString(dictionary2));
like image 196
Andrey Shchekin Avatar answered Oct 04 '22 08:10

Andrey Shchekin


using Linq:

Dictionary.All(e => AnotherDictionary.Contains(e))
like image 24
Toodleey Avatar answered Oct 04 '22 09:10

Toodleey