Search code examples
c#assertionfluent-assertions

Why did fluent assertion fail but Assert passed for an enum?


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 }

Solution

  • 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);