Asserting if a NameValueCollection is equivalent

时光毁灭记忆、已成空白 提交于 2019-12-11 03:19:47

问题


Does anyone know of a good way to assert if a NameValueCollection is equivalent? At the moment I'm using NUnit, but CollectionAssert.AreEquivalent() seems to only assert the keys. Not the keys and the values.

I wrote this little piece of code to help me out, but it would be nice if there was something out-of-the-box that could do the same.

private static void AssertNameValueCollectionAreEquivalent(NameValueCollection expectedCollection, NameValueCollection collection)
{
   // Will evaluate keys only
   CollectionAssert.AreEquivalent(expectedCollection, collection);

   foreach (string namevalue in collection)
   {
      Assert.AreEqual(expectedCollection[namevalue], collection[namevalue]);
   }
}

回答1:


how about convert it to Dictionary and assert as:

CollectionAssert.AreEquivalent(
    expectedCollection.AllKeys.ToDictionary(k => k, k => expectedCollection[k]),
    collection.AllKeys.ToDictionary(k => k, k => collection[k])); 



回答2:


I am a fan of Fluent Assertions for NUnit. not only is the syntax fluent and more concise, but they make a number of assertions easier, and this is one of them.

Consider:

var c = new NameValueCollection();
var c2 = new NameValueCollection();

c.Add("test1", "testvalue1");
c.Add("test2", "testvalue2");

c2.Add("test1", "testvalue1");
c2.Add("test2", "testvalue2");

c.Should().BeEquivalentTo(c2); // assertion succeeds


来源:https://stackoverflow.com/questions/10991292/asserting-if-a-namevaluecollection-is-equivalent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!