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

标签 c# comparison nunit

在我的代码中测试某些矢量运算时,我必须检查是否与某些公差值相等,因为 float 值可能不完全匹配。

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

Assert.That(somevector.EqualWithinTolerance(new Vec3(0f, 1f, 0f)), Is.True);

取而代之的是:

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)));

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

Expected: True
But was:  False

取而代之的是:

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();
        }
    }

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

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)).Using(fuzzyVectorComparer));

需要更多的输入,但这是值得的。

关于c# - 使用自定义比较函数断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11453846/

相关文章:

tsql - MS SQL 浮点十进制比较问题

c# - 如何使用 NUnit 测试回调

nunit - Selenium,Nunit 最佳实践?

c# - .Net 应用程序性能优化器

c# - 使用 WCF 服务时,从 using 语句中返回是否是一种好的形式?

时间:2019-03-08 标签:c#webapihttpgetattribute

perl - 我如何比较 Perl 中的 md5 校验和?

python - 比较字符串列表以查找序列的缺失值

c# - WPF:使用 .ico 文件作为工具栏的图像?或者需要转换为 XAML?

c# - 使用 AutoFixture 中的 AutoMock 对构造函数中的响应式(Reactive)代码进行单元测试?