HardLuck
HardLuck

Reputation: 1577

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

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)

Upvotes: 5

Views: 4642

Answers (2)

alelom
alelom

Reputation: 3008

After looking for a while for a more up-to-date answer, here's the solution in 2024. It involves using IEquivalencyStep to implement a custom class to be referenced through the Using() method of the options of BeEquivalentTo().

In the following example, I'm testing with a Dictionary with some string key in it, in order to show that it works with types that include a string in them.

[Test]
public void StringNullOrEmpty()
{
    Dictionary<string, object> dict1 = new();
    Dictionary<string, object> dict2 = new();
    dict1["SomeString"] = null;
    dict2["SomeString"] = "";

    dict1.Should().BeEquivalentTo(dict2, opt => opt.Using(new NullStringEquivalencyStep()));
}

private class NullStringEquivalencyStep : IEquivalencyStep
{
    public EquivalencyResult Handle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator)
    {
        if (comparands.GetExpectedType(context.Options) == typeof(string)
            && string.IsNullOrEmpty(comparands.Subject as string)
            && string.IsNullOrEmpty(comparands.Expectation as string))
        {
            return EquivalencyResult.AssertionCompleted;
        }

        return EquivalencyResult.ContinueWithNext;
    }
}

Upvotes: 0

Dennis Doomen
Dennis Doomen

Reputation: 8899

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.

Upvotes: 10

Related Questions