Skip to content

Allow IEqualityComparer in string equality assertion #2339

@bart-vmware

Description

@bart-vmware

Background and motivation

I'm trying to assert two strings are equal using a custom comparer. The code below works, though it would be nice if the cast to object wouldn't be necessary and Be() could be used instead of BeEquivalentTo().

using System.Text.RegularExpressions;
using FluentAssertions;

string logLines = @"one\ntwo\nthree";
string expected = @"one\r\ntwo\r\nthree";

((object)logLines).Should().BeEquivalentTo(expected, options => options.Using(IgnoreLineEndingsComparer.Instance));

public sealed class IgnoreLineEndingsComparer : IEqualityComparer<string>
{
    public static readonly IgnoreLineEndingsComparer Instance = new();

    public bool Equals(string x, string y)
    {
        if (x == y)
        {
            return true;
        }

        if (x == null || y == null)
        {
            return false;
        }

        var xLines = Regex.Split(x, "\r\n|\r|\n");
        var yLines = Regex.Split(x, "\r\n|\r|\n");

        return xLines.SequenceEqual(yLines);
    }

    public int GetHashCode(string obj)
    {
        return obj.GetHashCode();
    }
}

API Proposal

public class StringAssertions<TAssertions> : ReferenceTypeAssertions<string, TAssertions>
    where TAssertions : StringAssertions<TAssertions>
{
    public AndConstraint<TAssertions> Be(string expected, IEqualityComparer<string> comparer,
        string because = "", params object[] becauseArgs);
}

API Usage

using System.Text.RegularExpressions;
using FluentAssertions;

string logLines = @"one\ntwo\nthree";
string expected = @"one\r\ntwo\r\nthree";

logLines.Should().Be(expected, IgnoreLineEndingsComparer.Instance);

Alternative Designs

No response

Risks

No response

Are you willing to help with a proof-of-concept (as PR in that or a separate repo) first and as pull-request later on?

No

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions