I'm trying to compare the precision of two numbers with some tolerance.
This is how it was being checked in nUnit:
Assert.That(turnOver, Is.EqualTo(turnoverExpected).Within(0.00001).Percent);
I'm trying to do the same in xUnit but this is all I've come up with:
double tolerance = 0.00001;
Assert.Equal(turnOver, turnoverExpected, tolerance);
This doesn't compile because Assert.Equal
doesn't take a 3rd argument of type double
.
Anyone got an idea of a nice way to do this in xUnit?
You'll have to implement IEquatable<T> for your objects, and then Assert. Equals will work. Assert. Same() compares by reference; it asserts that Obj1 and Obj2 are the same object rather than just looking the same.
In xUnit and many other testing frameworks, assertion is the mean that we conduct our test. In other word we assert an expectation that something is true about a piece of code. There are many different types of assertion in xUnit that we can use.
You probably slightly misunderstood the last parameter(precision) in Assert.Equal(expected, actual, precision)
method.
/// <param name="precision">The number of decimal places (valid values: 0-15)</param>
So, for instance, if you want to compare 0.00021
with 0.00022
and you are interested in comparing only 4 decimal places, you can do this (it will return true
):
Assert.Equal(0.00021, 0.00022, 4); // true
This will return false
:
Assert.Equal(0.00021, 0.00022, 5); // false
You could use FluentAssertions
float value = 3.1415927F;
value.Should().BeApproximately(3.14F, 0.01F);
You can use Assert.InRange()
, where the signature is
public static void InRange<T>(T actual, T low, T high) where T : IComparable
I was porting some tests from MS Test V1 to xUnit and noticed that the Assert
with a Delta wasn't working the same as the one in xUnit.
To solve this, I decompiled the one from MS Test and made my own version:
internal static class DoubleAssertion
{
const Double delta = 0.00001;
public static void Equal(Double expected, Double actual, String message = null)
{
if (Math.Abs(expected - actual) > delta)
{
var deltaMessage = $"Expected a difference no greater than <{delta.ToString(CultureInfo.CurrentCulture.NumberFormat)}>";
if (!String.IsNullOrWhiteSpace(message))
message = message + Environment.NewLine + deltaMessage;
else
message = deltaMessage;
throw new DoubleException(
expected: expected.ToString(CultureInfo.CurrentCulture.NumberFormat),
actual: actual.ToString(CultureInfo.CurrentCulture.NumberFormat),
message: message);
}
}
}
public class DoubleException : AssertActualExpectedException
{
public DoubleException(
String expected,
String actual,
String message)
: base(expected, actual, message)
{
}
}
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