我们如何使用ASSERT_NEAR或ASSERT_DOUBLE_EQ float 比较而不在谓词格式化程序函数中使用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的浮点比较而不是我自己的...?
最佳答案
您可以只用几行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的末尾
关于c++ - 是否可以在googletest的谓词格式化程序中使用ASSERT_NEAR,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34947167/