在GoogleTest中方便的方法进行双重比较不等于?

Bra*_*ran 8 c++ tdd unit-testing googletest

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

也许我在没有ASSERT_DOUBLE_NE的情况下错过了一个简单的方法吗?

Vla*_*sev 6

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

EXPECT_THAT(value, FloatEq(1));
EXPECT_THAT(another_value, Not(DoubleEq(3.14)));
Run Code Online (Sandbox Code Playgroud)


def*_*ode 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);   
}
Run Code Online (Sandbox Code Playgroud)