Convenient method in GoogleTest for double comparison not equal?

I am looking for something similar to ASSERT_EQ / ASSERT_NE for ASSERT_DOUBLE_EQ.

Perhaps I am missing a simple way to do this without having ASSERT_DOUBLE_NE?

+6
c ++ unit-testing tdd googletest
source share
3 answers

You can use the companion mocking structure of Google Mock. It has a powerful matchers library (a la Hamcrest) that you can use with the EXPECT_THAT / ASSERT_THAT macros:

EXPECT_THAT(value, FloatEq(1)); EXPECT_THAT(another_value, Not(DoubleEq(3.14))); 
+6
source share

You seem unlucky. However, you can add it yourself. I built the following code using ASSERT_DOUBLE_EQ and ASSERT_NE as a template.

 #define ASSERT_DOUBLE_NE(expected, actual)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointNE<double>, \ expected, actual) // Helper template function for comparing floating-points. // // Template parameter: // // RawType: the raw floating-point type (either float or double) // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template <typename RawType> AssertionResult CmpHelperFloatingPointNE(const char* expected_expression, const char* actual_expression, RawType expected, RawType actual) { const FloatingPoint<RawType> lhs(expected), rhs(actual); if ( ! lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } StrStream expected_ss; expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << expected; StrStream actual_ss; actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << actual; Message msg; msg << "Expected: (" << expected_expression << ") != (" << actual_expression << "), actual: (" << StrStreamToString(expected_ss) << ") == (" << StrStreamToString(actual_ss) << ")"; return AssertionFailure(msg); } 
+1
source share

instead of creating a new CmpHelperFloatingPointNE helper, you can simply define the macro as the inverse of the existing helper:

 #include "gtest/gtest.h" #define ASSERT_FLOAT_NE(val1, val2) ASSERT_PRED_FORMAT2( \ !::testing::internal::CmpHelperFloatingPointEQ<float>, val1, val2 \ ) #define ASSERT_DOUBLE_NE(val1, val2) ASSERT_PRED_FORMAT2( \ !::testing::internal::CmpHelperFloatingPointEQ<double>, val1, val2 \ ) 

This is not as graceful as the deft_code solution, because when the statement fails, there are no specific details such as the "expected value" and "actual value", just the line number and the statement file. However, for my purposes, the line number was enough.

0
source share

All Articles