c++ - PrintTo 用于 Google Test 中的指针

标签 c++ googletest

如果测试失败,我可以指定如何显示对象的内容。为此,我为该类定义了函数 PrintTo。结果如愿(字符串 MyObject as object):

x.cpp:17: Failure
Value of: foo1
Expected: has foo <MyObject as object>
  Actual: <MyObject as object> (of type Foo)

不幸的是,我找不到如何对指向对象的指针执行相同的操作。我得到的是默认输出,而不是自定义字符串 MyObject as pointer:

x.cpp:22: Failure
Value of: pfoo1
Expected: has foo 0x8058330
  Actual: 0x8058320 (of type Foo*)

作为解决方法,我可以取消引用指针,但我想知道是否有直接的解决方案,即在指针上重载 PrintTo

#include <gmock/gmock.h>

struct Foo { };

void PrintTo(const Foo& value, ::std::ostream* os) {
  *os << "<MyObject as object>";
}

void PrintTo(const Foo* value, ::std::ostream* os) {
  *os << "<MyObject as pointer>";
}

MATCHER_P(HasFoo, expected, "") { return false; }

TEST(Foo, Object) {
  Foo foo1, foo2;
  ASSERT_THAT(foo1, HasFoo(foo2));
}

TEST(Foo, Pointer) {
  Foo *pfoo1 = new Foo(), *pfoo2 = new Foo();
  ASSERT_THAT(pfoo1, HasFoo(pfoo2));
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

最佳答案

按照@AndyG 和@olaf-dietsche 的建议,应该删除前导的const。这些工作:

Foo* 值

Foo* 常量值

而这些不是:

const Foo* 值

const Foo* 常量值

const Foo*& value

关于c++ - PrintTo 用于 Google Test 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839760/

相关文章:

c++ - 使用 googletest 测试 const 行为

c++ - 在 Googletest 单元测试中禁用自动捕获 C++ 异常

c++ - 谷歌模拟 : mock fstream object and control of execution in test

c++ - 在游戏中更改游戏控制

c# - 如何从 C# 将 PWCHAR 传递到 C++ dll

c++ - 从 MSI 获取模块文件名

C++:当你有指针时,为什么需要引用?

c++ - 改变线程任务?

c++ - 如何在运行时 C++ 中包含头文件和函数?

c++ - 与 C++ 中带有引号的硬编码字符串进行比较