VS2010 Unit test fails while result is correct
I've made a demo project on testing with VS2010 at the company I work at. As input for the tests a little math calculation class: MathOps. MathOps can throw some exceptions and whatnot. However, when I was setting up the unit tests I came acrosse a unit test which seems to behave very oddly.
The MathOps object is called target and is initialized in a test initialization method to demonstrate what it might be used for.
Private target As MathOps = Nothing
<TestInitialize()> _
Public Sub MyTestInitialize()
target = New MathOps()
End Sub
The test which is misbehaving is the following one:
'''<summary>
'''A test for MathOps.add
'''</summary>
<TestMethod()> _
Public Sub addTest()
Dim first As Double = 开发者_StackOverflow社区2.3
Dim second As Double = 3.4
Dim expected As Double = 5.7
Dim actual As Double
actual = target.add(first, second)
Assert.AreEqual(expected, actual)
End Sub
When I use addition terms which result in 5.7 being the expected/result value, the assertion fails, even though the code produces the right result.
Assert.AreEqual failed. Expected:<5,7>. Actual:<5,7>.
If I make it 5.7000001 by adding 3.4000001 instead of 3.4 the test passes.
Does anyone know the cause of this error?
Don't ever expect precise results from floating point operations; floating-point arithmetic is inherently susceptible to rounding problems like this one. Check the result using an error threshold instead.
精彩评论