Error with EXPECT_EQ for sum of double or float
From https://testing.googleblog.com/2008/10/tott-floating-point-comparison.html
When comparing floating-point values, checking for equality might lead to unexpected results. Rounding errors can lead to a result that is close to the expected one, but not equal. As a consequence, an assertion might fail when checking for equality of two floating-point quantities even if the program is implemented correctly.
The Google C++ Testing Framework provides functions for comparing two floating-point quantities up to a given precision.
ASSERT_FLOAT_EQ(expected, actual);
ASSERT_DOUBLE_EQ(expected, actual);
EXPECT_FLOAT_EQ(expected, actual);
EXPECT_DOUBLE_EQ(expected, actual);
In your case,
TEST(simpleSum, sumOfFloat)
{
EXPECT_DOUBLE_EQ(4.56, sum(0.56, 4.0));
}
See documentation for Floating Point Comparison
EXPECT_EQ
uses exact match.
But you cannot match two floating numbers exactly. (at least with ease.)
You can use EXPECT_FLOAT_EQ
or EXPECT_DOUBLE_EQ
. (with heuristic bounds)
Also, you may use EXPECT_NEAR
with specific bounds.
Use EXPECT_NEAR
or the DoubleEq
matcher instead. Floating point operations can lead to rounding errors which makes the results ever so slightly different.