Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用自定义比较函数断言_C#_Comparison_Nunit - Fatal编程技术网

C# 使用自定义比较函数断言

C# 使用自定义比较函数断言,c#,comparison,nunit,C#,Comparison,Nunit,在我的代码中测试一些向量操作时,我必须检查是否与某个公差值相等,因为浮点值可能不完全匹配 这意味着我的测试断言如下: Assert.That(somevector.EqualWithinTolerance(new Vec3(0f, 1f, 0f)), Is.True); Expected: True But was: False Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)).Using(fuzzyVectorCompare

在我的代码中测试一些向量操作时,我必须检查是否与某个公差值相等,因为
浮点值可能不完全匹配

这意味着我的测试断言如下:

Assert.That(somevector.EqualWithinTolerance(new Vec3(0f, 1f, 0f)), Is.True);
Expected: True
But was:  False
Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)).Using(fuzzyVectorComparer));
与此相反:

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)));
Expected: 0 1 0
But was:  1 0 9,536743E-07
这意味着我的例外情况如下:

Assert.That(somevector.EqualWithinTolerance(new Vec3(0f, 1f, 0f)), Is.True);
Expected: True
But was:  False
Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)).Using(fuzzyVectorComparer));
与此相反:

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)));
Expected: 0 1 0
But was:  1 0 9,536743E-07
让我们更难理解出了什么问题


如何使用自定义比较函数并仍然获得一个很好的异常?找到了答案。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();
        }
    }
打字要多一些,但这是值得的