2

I am having trouble finding why the assertion 1 fails but assertion 2 passed:

var a = Test.test1;
var b = Test.test1;
a.Should().BeSameAs(b); //1
Assert.Equal(a, b);     //2

Test is an enum like following:

enum Test { test1, test2 }
Kit
  • 20,354
  • 4
  • 60
  • 103
Yituo
  • 1,458
  • 4
  • 17
  • 26

1 Answers1

6

Should() for an enum resolves to ObjectAssertions which boxes the enum into an object. For ObjectAssertions the expected parameter of BeSameAs is also of type object.

So a.Should().BeSameAs(b) boxes a and b into two different objects and then checks that those two objects refers to the exact same object in memory.

If you want to assert that a and b are the same enum, you should use

a.Should().Be(b);
Jonas Nyrup
  • 2,376
  • 18
  • 25
  • 2
    Yes. Maybe the asker knows the same behavior with the static method inherited from `System.Object`. If you say `var q = ReferenceEquals(a, b);` then `q` will be `false`. Two different boxes with the same content. – Jeppe Stig Nielsen Jan 08 '19 at 21:10
  • @ Jeppe, The comparison with ReferenceEquals(a, b) really clarifies the issue. Thanks! – Yituo Jan 08 '19 at 22:52