I have two different ways to calculate a value. Once both methods run, I get the following:
decimal a = 145.2344;
decimal b = 145.2345;
I have a unit test:
Assert.AreEqual(a,b);
I want to be able to account for a +/- .0001 difference. How can I add this rule?
The greater a decimal is, the closer it is to one whole. The smaller a decimal is the farther it is from one whole. The first thing you need to look at is the digit number in each decimal. These each have two digits in them, so you can compare them right away.
In NUnit's constraint model, you can do this:
Assert.That(Math.Abs(a-b), Is.LessThan(0.0001M));
Better yet, make it a function:
void AssertDiff(decimal a, decimal b, decimal diff = 0.0001) {
Assert.That(Math.Abs(a-b), Is.LessThan(diff));
}
EDIT : In MS Unit Test Framework, do this:
void AssertDiff(decimal a, decimal b, decimal diff = 0.0001) {
Assert.IsTrue(Math.Abs(a-b) < diff);
}
Simple:
if (Math.Abs(a-b) < 0.0001m)
// equal
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