Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert with custom comparison function

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?

like image 509
João Portela Avatar asked Jul 12 '12 14:07

João Portela


1 Answers

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.

like image 185
João Portela Avatar answered Oct 31 '22 02:10

João Portela