Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asserting if a NameValueCollection is equivalent

Tags:

c#

nunit

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]);
   }
}
like image 367
Markus Avatar asked Feb 03 '26 07:02

Markus


2 Answers

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])); 
like image 95
Damith Avatar answered Feb 05 '26 20:02

Damith


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
like image 31
moribvndvs Avatar answered Feb 05 '26 21:02

moribvndvs