我正在为ASSERT_DOUBLE_EQ寻找类似于ASSERT_EQ / ASSERT_NE的东西。
也许我在没有ASSERT_DOUBLE_NE的情况下错过了一种简单的方法吗?
答案 0 :(得分:6)
您可以使用随播模拟框架Google Mock。它有一个强大的匹配器库(la Hamcrest),可以与EXPECT_THAT / ASSERT_THAT宏一起使用:
EXPECT_THAT(value, FloatEq(1));
EXPECT_THAT(another_value, Not(DoubleEq(3.14)));
答案 1 :(得分: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);
}
答案 2 :(得分: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的解决方案那么优雅,因为当断言失败时,没有特定的细节,如“期望值”和“实际值”,只是断言的行号和文件。不过,就我的目的而言,行号已足够。