When testing some vector operations in my code I have to check for equality with some tolerance value because the float values may not be an exact match.
Which means that my test asserts are like this:
Assert.That(somevector.EqualWithinTolerance(new Vec3(0f, 1f, 0f)), Is.True);
Instead of this:
Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)));
And that means that my exceptions are like this:
Expected: True
But was:  False
Instead of this:
Expected: 0 1 0
But was:  1 0 9,536743E-07
Making it slightly harder to understand what went wrong.
How do I use a custom comparison function and still get a nice exception?
Found the answer.  NUnit EqualConstraint has a method with the expected name: Using.
So I just added this class:
    /// <summary>
    /// Equality comparer with a tolerance equivalent to using the 'EqualWithTolerance' method
    /// 
    /// Note: since it's pretty much impossible to have working hash codes
    /// for a "fuzzy" comparer the GetHashCode method throws an exception.
    /// </summary>
    public class EqualityComparerWithTolerance : IEqualityComparer<Vec3>
    {
        private float tolerance;
        public EqualityComparerWithTolerance(float tolerance = MathFunctions.Epsilon)
        {
            this.tolerance = tolerance;
        }
        public bool Equals(Vec3 v1, Vec3 v2)
        {
            return v1.EqualWithinTolerance(v2, tolerance);
        }
        public int GetHashCode(Vec3 obj)
        {
            throw new NotImplementedException();
        }
    }
I instantiated it and used it like this:
Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)).Using(fuzzyVectorComparer));
It's more typing, but it's worth it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With