-1

I have tests which show the following xUnit.net output:

[xUnit.net 00:00:07.1166826]       Expected: HashSet<License> [Comp.Licensing.Web.Model.License [5d8104ef-f707-4a40-9d68-463bf9f8b0f9], Comp.Licensing.Web.Model.License [d586fc23-bba6-474c-82a2-226484d7fb81]]
[xUnit.net 00:00:07.1172482]       Actual:   HashSet<License> [Comp.Licensing.Web.Model.License [d586fc23-bba6-474c-82a2-226484d7fb81], Comp.Licensing.Web.Model.License [5d8104ef-f707-4a40-9d68-463bf9f8b0f9]]

What I don't understand is why this test is failing, and seemingly the reason is that the HashSet is out of order.

Specifically, it appear that the Actual is exactly the same as the **Expected.

Actual:

HashSet<L> [Stuff [abc], Stuff [123]]

Expected:

HashSet<L> [Stuff [123], Stuff [abc]]

On the doc for HashSet, it says

A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

Are my tests being run by something that's not using the same equality check for HashSet?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
r12
  • 1,712
  • 1
  • 15
  • 25
  • 2
    How about posting your tests so that we can see what may be wrong instead of trying to guess... – L.B Aug 02 '17 at 22:35
  • 1
    Are you checking that two HashSet object references are the same object, or that two HashSet objects have the same contents? What kind of equality are you testing for? – hatchet - done with SOverflow Aug 02 '17 at 22:38
  • Sorry @L.B, I'll put an edit explaining my confusion. What I don't understand is that the **Expected** HashSet in that message is the same as the **Actual** – r12 Aug 02 '17 at 22:42
  • @hatchet That two HashSets have the same contents – r12 Aug 02 '17 at 22:45
  • 1
    @rt2 Just copy this code and test it..It is 3 lines of code. VS will help you. `var equal1 = new HashSet(new[] { 1, 2 }) == new HashSet(new[] { 1, 2 }); var equal2 = new HashSet(new[] { 1, 2 }).SequenceEqual(new HashSet(new[] { 2, 1 })); var equal3 = new HashSet(new[] { 1, 2 }).OrderBy(x=>x).SequenceEqual(new HashSet(new[] { 2, 1 }).OrderBy(x=>x));` – L.B Aug 02 '17 at 22:47
  • "Are my tests being run by something that's not using the same equality check for HashSet?" What are you using to test the equality of your HashSets? – ILMTitan Aug 02 '17 at 22:52

1 Answers1

2

HashSet does not override Equals, and will use object.Equals, which is reference equality.

HashSet give no guarantee on the order of the elements.

If you are using Assert.Equal, then the order of the collections matter.

Instead use CollectionAssert.AreEquivalent.

Source: xUnit : Assert two List<T> are equal?

ILMTitan
  • 10,751
  • 3
  • 30
  • 46