c++ - cppunit 断言失败时如何显示十六进制值

标签 c++ unit-testing cppunit

我使用 CPPUNIT_ASSERT_EQUAL(a, b) 来检查值 a 和 b。 a 和 b 是 unsigned char 类型。因此,当此断言失败时,它将显示预期值和实际值。因为类型是unsigned char,所以期望值和实际值会显示为字符。例如,35 将显示为#。但这不是我想要的。当然, CPPUNIT_ASSERT_EQUAL((int)a, (int)b) 可能是一个解决方案,但它看起来很奇怪。另外,如果这些值显示为十六进制格式会更好。但我不知道如何达到这一点。如果有人给出答案,我们将不胜感激。

最佳答案

我认为实现此效果的唯一方法是将 a 和/或 b 调整为合适的类型,该类型可以进行所需的比较,但格式不同于无符号字符。这可能看起来像这样:

template <typename T>
struct as_hex_t
{
    as_hex_t(T const& value): d_value(value) {}
    T const& d_value;
};
bool operator== (as_hex_t<T> const& v0, as_hex_t<T> const& v1) {
    return v0.d_value == v1.d_value;
}
std::ostream& operator<< (std::ostream& out, as_hex_t const& value) {
    return out << std::hex << unsigned(value.d_value) << std::dec;
}
template <typenane T>
as_hex_t<T> as_hex(T const& val) { return as_hex_t<T>(val); }

CPPUNIT_ASSERT_EQUAL(as_hex(a), as_hex(b));

显然,适配值的类型只需要在合适的地方定义一次,就可以进入合适的宏。我不知道 CPPUNIT,但我可以想象某处存在这样的东西。

关于c++ - cppunit 断言失败时如何显示十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967948/

相关文章:

c++ - g 编译器错误与 map<T, int>::iterator

c++ - 我正在研究 Arduino Uno。错误 : "' RX' not declared in the scope ."and "duplicate case value"for switch case

c - 在 C 中初始化大块 double 的最有效方法

c++ - 如何对回调函数抛出的异常进行单元测试

c++ - 点云库不适用于Visual Studio 2019

C++:队列中的第一个字符错误

unit-testing - 是否可以将 golang 单元测试结果打印到文件中?

unit-testing - 如何在不暴露访问器的情况下对结构进行单元测试

linux - 当我尝试在 Linux 上运行可执行文件时,我得到 "error while loading shared libraries"

c++ - Sonar 无法读取我的 CPPUnit 报告