我们如何使用ASSERT_NEAR或ASSERT_DOUBLE_EQ浮动比较而不使用googletest内部的谓词格式化函数?
template<typename A, typename B>
::testing::AssertionResult assertNearArrays(const char * a_expr,
const char * b_expr,
const A & a,
const B & b,
PREC absError = 1e-6){
test each value of a with b
using ASSERT_NEAR(a[i],b[i], 1e-6)
}
我觉得这不会奏效,我需要写一个自己的比较来回复AssertionResult
或AssertionFailure
。
但依靠googletest而不是我自己的浮点数比较会很好......?
答案 0 :(得分:3)
您只能在几行C ++代码中编写此类测试:
template<typename T>
bool is_near(T val1, T val2, T abs_error) {
const T diff = std::abs(val1 - val2);
return diff <= abs_error:
}
你真的需要完全遵循gtest ASSERT_NEAR的作用吗?您可能希望在失败时提供有关ASSERT_NEAR将执行的添加信息,例如:
if (!is_near(a[i], b[i], absError))
return AssertionFailure()
<< "The difference between a[i] and b[i]"
<< " is " << (a[i] - b[i]) << ", which exceeds absError, where\n"
<< "a[i] evaluates to " << a[i] << ",\n"
<< "b[i] evaluates to " << b[i]<< ", and\n"
<< "absError evaluates to " << absError << ", and\n"
<< "i evaluates to " << i << ".";
并且返回AssertionSuccess();在assertNearArrays的末尾