PrintTo for Google Test中的指针

时间:2016-10-03 20:20:08

标签: 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();
}

1 个答案:

答案 0 :(得分:1)

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

Foo* value

Foo* const value

而这些不是:

const Foo* value

const Foo* const value

const Foo*& value