如果测试失败,我可以指定如何显示对象的内容。为此,我为该类定义了函数 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/