如何在单元测试中断言字典

mat*_*nik 9 c# collections dictionary unit-testing

你知道我怎么能断言两种类型的词典

Dictionary<string,List<string>>
Run Code Online (Sandbox Code Playgroud)

在我的单元测试项目中?

我尝试使用CollectionsAssert,但它并没有为我工作.我想这需要简单的字典作为参数(例如Dictionary<string,string>).我猜我的问题来自字典的第二个参数.你知道我怎么能断言那些两本词典?

Too*_*eey 11

使用Linq:

Dictionary.All(e => AnotherDictionary.Contains(e))
Run Code Online (Sandbox Code Playgroud)

  • 这只是检查 AnotherDictionary 是 Dictionary 的超集。并不是说它们是平等的。 (2认同)

And*_*kin 11

一种可以为您提供良好错误消息的方法:

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));
Run Code Online (Sandbox Code Playgroud)