xunit.net - double [,]比较

时间:2014-05-01 18:52:57

标签: unit-testing xunit.net

我的单元测试失败消息是:

Result Message: 
Assert.Equal() Failure
Position: First difference is at position 0
Expected: Double[,] { 0,888888888888889, 1,33333333333333, 1,33333333333333, 2,66666666666667 }
Actual:   Double[,] { 0,888888888888889, 1,33333333333333, 1,33333333333333, 2,66666666666667 }

我知道如果你比较双数,你必须指定精度,所以我的解决方法是:

Assert.Equal(_sA.ToArray(), result.ToArray(), new Comparer());

class Comparer : IEqualityComparer<double[,]>
{
    public bool Equals(double[,] x, double[,] y)
    {
        if (x.GetLength(0) != y.GetLength(0) || x.GetLength(1) != y.GetLength(1))
            return false;

        for (var i = 0; i < x.GetLength(0); ++i)
        {
            for(var j = 0; j < x.GetLength(1); ++j)
            if (!isEqual(x[i, j], y[i, j]))
                return false;
        }

        return true;
    }

    private bool isEqual(double x, double y)
    {
      const double epsilon = 1e-5;
      return Math.Abs(x - y) <= epsilon * Math.Abs(x);
    }
}

有没有更好,更简单的解决方案?

1 个答案:

答案 0 :(得分:2)

来自XUnit代码库

/// <summary>
/// Verifies that two <see cref="T:System.Double" /> values are equal, within the number of decimal
/// places given by <paramref name="precision" />.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="precision">The number of decimal places (valid values: 0-15)</param>
/// <exception cref="T:Xunit.Sdk.EqualException">Thrown when the values are not equal</exception>
public static void Equal(double expected, double actual, int precision)