0

So I generate an empty Dictionary<string,string> to compare to my test result, and then I do this:

Assert.AreEqual(retval, temp);

And it fails even though they contain the same exact data. I've also tried using IsTrue like this: Assert.IsTrue(retval.Equals(temp)); and that fails too even if they are the same.

How can I compare just the elements, not the same memory location which I'm assuming it's doing?

Thanks.

Tom Robinson
  • 8,348
  • 9
  • 58
  • 102
slandau
  • 23,528
  • 42
  • 122
  • 184

2 Answers2

1

You could do Assert.IsTrue(retval.SequenceEqual(temp)), although this will also require the order of elements in the dictionaries to be the same. I'm not sure if you want your test for equality to be that strict.

See this question and its answers for ways to compare the contents of the dictionaries regardless of sequence.

Community
  • 1
  • 1
Jeff Ogata
  • 56,645
  • 19
  • 114
  • 127
  • Since the order of elements in a dictionary is undefined `SequenceEqual` is never guaranteed to work. – CodesInChaos Oct 22 '11 at 16:52
  • @CodeInChaos, does that mean the order might change between enumerations even if the contents of the dictionary aren't modified? I'm not disagreeing with you, just trying to understand why `SequenceEqual` wouldn't work. – Jeff Ogata Oct 22 '11 at 21:36
  • It won't change between enumerations, but it's not guaranteed that two instances of dictionary that contain the same elements will enumerate in the same order. In practice it probably will have the same order if you do all modifications to both of them in the same order, but it's not guaranteed to work. – CodesInChaos Oct 22 '11 at 22:21
1

Have you looked at

.NET Dictionaries have same keys and values, but aren't "equal"

Looks like a pretty complete answer.

Community
  • 1
  • 1
Dean
  • 552
  • 4
  • 12
  • Order matters here, I just want to compare contained elements. – slandau Oct 22 '11 at 19:00
  • @Dean has the right idea here. You can't compare equality of collections in MSTest unless you use the CollectionAssert methods. –  Oct 23 '11 at 18:28