How can I compare null and string.Empty (or "") in fluent assertions?

c#, fluent-assertions, integration-testing

Solution

What you can do is to override the behavior for properties of type `string` like this:

callResult.ShouldBeEquivalentTo(centreResponse, opt => opt
          .Excluding(r => r.DateOpen)
          .Using<string>(ctx => CompareStrings(ctx)).WhenTypeIs<string>());       

public void CompareStrings(IAssertionContext<string> ctx)
{
    var equal = (ctx.Subject ?? string.Empty).Equals(ctx.Expectation ?? string.Empty);

    Execute.Assertion
        .BecauseOf(ctx.Because, ctx.BecauseArgs)
        .ForCondition(equal)
        .FailWith("Expected {context:string} to be {0}{reason}, but found {1}", ctx.Subject, ctx.Expectation);
}    

You can clean this up a bit by encapsulating the `CompareStrings` method in an implementation of `IAssertionRule`. See the `RelaxingDateTimeAssertionRule` in the unit tests of FluentAssertions here.

You can add that custom assertion rule as the default for all assertions on your the type of your `callResult` variable, but I still have to add something to allow global defaults.

Problem

I have two objects of the same type, the type has a string field, in the first object the value is null, in the second one the value is "", how can I force fluent assesrtions to assume that this is correct? Assesrtion itself: ``` callResult.ShouldBeEquivalentTo(centreResponse, opt => opt.Excluding(r => r.DateOpen)); ``` here the exception is raised, stating the the expected value is null, the real one is "" (or vice versa)

Original source