9

我正在为 ASSERT_DOUBLE_EQ 寻找类似于 ASSERT_EQ / ASSERT_NE 的东西。

也许我错过了一种没有 ASSERT_DOUBLE_NE 的简单方法?

4

3 回答 3

7

您可以使用配套的模拟框架 Google Mock。它有一个强大的匹配器库(a la Hamcrest),您可以将其与 EXPECT_THAT/ASSERT_THAT 宏一起使用:

EXPECT_THAT(value, FloatEq(1));
EXPECT_THAT(another_value, Not(DoubleEq(3.14)));
于 2010-09-03T16:53:49.110 回答
1

看来你运气不好。但是,您可以自己添加一个。我使用 ASSERT_DOUBLE_EQ 和 ASSERT_NE 作为模式构建了以下代码。

#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);   
}
于 2010-08-18T19:32:31.037 回答
0

而不是创建一个新的 CmpHelperFloatingPointNE 帮助器,您可以将宏定义为现有帮助器的逆:

#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 \
)

这不像 deft_code 的解决方案那样优雅,因为当断言失败时,没有“预期值”和“实际值”之类的具体细节,只有断言的行号和文件。不过,就我的目的而言,行号就足够了。

于 2016-06-09T16:18:11.553 回答