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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Since the order of elements in a dictionary is undefined SequenceEqual is never guaranteed to work.
@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.
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.
1

Have you looked at

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

Looks like a pretty complete answer.

2 Comments

Order matters here, I just want to compare contained elements.
@Dean has the right idea here. You can't compare equality of collections in MSTest unless you use the CollectionAssert methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.