Fluent Assertions: Compare two numeric collections approximately
Asked Answered
F

2

10

I have two arrays of double. Is there a way using FluentAssertions to compare the arrays element-by-element, using the .BeApproximately() technique?

One range value would suffice for the entire array.

Example:

double[] source = { 10.01, 8.01, 6.01 };
double[] target = { 10.0, 8.0, 6.0  };

// THE FOLLOWING IS NOT IMPLEMENTED
target.Should().BeApproximately(source, 0.01);   

Is there an alternative approach?

Fish answered 11/6, 2013 at 22:4 Comment(0)
F
12

There's an overload on the generic collection assertions that takes a Func that you can use to apply any predicate during comparison. With that, you could do something like:

source.Should().Equal(target, (left, right) => AreEqualApproximately(left, right, 0.01));

The only thing you need to do is to create that method yourself.

Francois answered 12/6, 2013 at 7:8 Comment(0)
F
2

I know it's preferable to compare the list but you could iterate it and compare them individually. I can't test the code right now but the following should work...

double[] source = { 10.01, 8.01, 6.01 };
double[] target = { 10.0, 8.0, 6.0  };

for(var i=0; i<source.Length; i++)
    target[i].Should().BeApproximately(source[i], 0.01)
Fairly answered 11/6, 2013 at 22:43 Comment(2)
Yes, that works, but I was hoping I could get all the violations to print out at once.Fish
Wish I could be more helpful but I don't know of a better way to do it. I'll upvote the question to see if we can get it more attention.Fairly

© 2022 - 2024 — McMap. All rights reserved.