Convenient method in GoogleTest for a double comparison of not equal?

那年仲夏 提交于 2019-12-19 17:35:05

问题


I'm looking for something similar to the ASSERT_EQ / ASSERT_NE for ASSERT_DOUBLE_EQ.

Maybe I'm missing an easy way of doing this without having a ASSERT_DOUBLE_NE?


回答1:


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

EXPECT_THAT(value, FloatEq(1));
EXPECT_THAT(another_value, Not(DoubleEq(3.14)));



回答2:


It looks like you're out of luck. However, you could add one yourself. I built the following code using ASSERT_DOUBLE_EQ and ASSERT_NE as a pattern.

#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);   
}



回答3:


instead of creating a new CmpHelperFloatingPointNE helper, you can just 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 deft_code's solution because when the assertion fails, there are no specific details like "expected value" and "actual value", just the line number and file of the assertion. For my purposes, though, the line number was enough.



来源:https://stackoverflow.com/questions/3515293/convenient-method-in-googletest-for-a-double-comparison-of-not-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!