How can I validate the sort order of list of objects, ordered by numeric property using Fluent Assertions?

40 Views Asked by At

Fluent assertions has a method to validate the sort order:

list.Should().BeInDescendingOrder(x => x.stringProperty);

OR

list.Should().BeInAscendingOrder(x => x.stringProperty);

The list I'm having has a numeric value based on which the objects within the list is sorted. This however doesnt work, since it sees the numeric value as a 'string' and the assertion fails. So, I want FluentAssertions to be made aware that its a numeric value and not a string.

For ex: if the object contains the following, the test fails:

List {
     obj1 ("stringProperty" : "20"), 
     obj2 ("stringProperty" : "100"), 
     obj3 ("stringProperty" : "300"),
     ..and so on }

I tried this but I want to convert it on the fly:

var numericList = List.Select(x => double.Parse(x.stringProperty)).ToList();

I want this coversion to happen in the original list and not in a seperate list since this will defeat the purpose of testing the Order of the List containing objects.

1

There are 1 best solutions below

0
Svyatoslav Danyliv On

You can introduce comparer which make conversion to double under hood:

public class NaturalOrderComparer<T> : IComparer<T>
{
    public static NaturalOrderComparer<T> Create(Func<T, string> propExtractor)
    {
        return new NaturalOrderComparer<T>(propExtractor);
    }

    public Func<T, string> PropExtractor { get; }

    public NaturalOrderComparer(Func<T, string> propExtractor)
    {
        PropExtractor = propExtractor;
    }

    public int Compare(T? x, T? y)
    {
        if (x == null || y == null)
            throw new NotImplementedException();

        var value1 = double.Parse(PropExtractor(x));
        var value2 = double.Parse(PropExtractor(y));

        return value1.CompareTo(value2);
    }
}

Then you can use it with FluentAssertions in the following way:

list.Should()
    .BeInDescendingOrder(NaturalOrderComparer<Order>.Create(x => x.stringProperty));