问题
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