My unit test fail message was:
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 }
I know that if you compare double numbers you must specify precision, so my workaround is:
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);
}
}
Is there any better, simpler solution?
From XUnit codebase
/// <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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With