Search code examples
c#fluent-assertions

Setting FluentAssertions Expectation on Nullable Enum


I have the following object (reduced to single property for brevity)

public class MyObject {
    public string MyProperty { get; set; }
}

and corresponding DTO

public class MyDto {
    public MyEnum? MyProperty {get; set;}
}

and my mapping is set up such that when string MyProperty is empty, the enum is set to null. Now I want to test this using FluentAssertions (there are lots of other properties as well), so I've tried setting the equivalency comparison behavior using the following

myDto.ShouldBeEquivalentTo(myObject, opt => opt.Using<MyEnum?>(ctx => ctx.Subject.Should().Be(null)).When(info => info.SelectedMemberPath.Equals(nameof(MyDto.MyProperty))));

But this doesn't work as I get the exception

Expected member MyProperty to be a System.String, but found a System.Nullable

What am I doing wrong?


Solution

  • I think you've found an edge case here. FluentAssertions treats enums and strings special, but doesn't handle nullable enums. The Using/WhenTypes doesn't support handling properties of different types. The only way to resolve that is to file a change request.