断言与自定义比较功能

Joã*_*ela 4 c# comparison nunit

在我的代码中测试一些向量操作时,我必须检查具有一些容差值的相等性,因为这些float值可能不完全匹配.

这意味着我的测试断言是这样的:

Assert.That(somevector.EqualWithinTolerance(new Vec3(0f, 1f, 0f)), Is.True);
Run Code Online (Sandbox Code Playgroud)

而不是这个:

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)));
Run Code Online (Sandbox Code Playgroud)

这意味着我的异常是这样的:

Expected: True
But was:  False
Run Code Online (Sandbox Code Playgroud)

而不是这个:

Expected: 0 1 0
But was:  1 0 9,536743E-07
Run Code Online (Sandbox Code Playgroud)

让它稍微难以理解出了什么问题.

我如何使用自定义比较功能仍然得到一个很好的例外?

Joã*_*ela 12

找到了答案.NUnit EqualConstraint有一个具有预期名称的方法:Using.

所以我刚刚添加了这个类:

    /// <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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我实例化它并像这样使用它:

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)).Using(fuzzyVectorComparer));
Run Code Online (Sandbox Code Playgroud)

它打字更多,但值得.