Gmock:保存传递参数的指针或在预期调用中按地址进行比较
Gmock: save a pointer of a passed argument or compare by address in expected call
假设我有一个方法
void Mock::foo(const A& obj);
并且我想检查它是用对象 obj
而不是它的副本调用的:
A obj;
EXPECT_CALL(mock, foo(obj));
mock->foo(obj);
我该如何检查?我找到 Address(m)
匹配器 here。但我无法在 ::testing
中找到它,即它无法编译。
如评论中所述,::testing::Address()
匹配器是在 GoogleTest 1.11 中引入的。
您可以改用 ::testing::Ref()
matcher, which does the same thing underneath (comparing addresses) and is available since at least GoogleTest 1.8 (see it online):
#include <gmock/gmock.h>
struct Data
{};
struct Mock
{
MOCK_METHOD(void, foo, (const Data& d), ());
};
struct ClassUnderTest
{
Mock* dependency;
void methodUnderTest(const Data& d)
{
dependency->foo(d);
}
void methodThatCopies(const Data& d)
{
Data copy = d;
dependency->foo(copy);
}
};
TEST(X, Correct)
{
Mock m;
Data d;
ClassUnderTest uut {&m};
EXPECT_CALL(m, foo(::testing::Ref(d)));
uut.methodUnderTest(d);
}
TEST(X, Fail)
{
Mock m;
Data d;
ClassUnderTest uut {&m};
EXPECT_CALL(m, foo(::testing::Ref(d)));
uut.methodThatCopies(d);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
假设我有一个方法
void Mock::foo(const A& obj);
并且我想检查它是用对象 obj
而不是它的副本调用的:
A obj;
EXPECT_CALL(mock, foo(obj));
mock->foo(obj);
我该如何检查?我找到 Address(m)
匹配器 here。但我无法在 ::testing
中找到它,即它无法编译。
如评论中所述,::testing::Address()
匹配器是在 GoogleTest 1.11 中引入的。
您可以改用 ::testing::Ref()
matcher, which does the same thing underneath (comparing addresses) and is available since at least GoogleTest 1.8 (see it online):
#include <gmock/gmock.h>
struct Data
{};
struct Mock
{
MOCK_METHOD(void, foo, (const Data& d), ());
};
struct ClassUnderTest
{
Mock* dependency;
void methodUnderTest(const Data& d)
{
dependency->foo(d);
}
void methodThatCopies(const Data& d)
{
Data copy = d;
dependency->foo(copy);
}
};
TEST(X, Correct)
{
Mock m;
Data d;
ClassUnderTest uut {&m};
EXPECT_CALL(m, foo(::testing::Ref(d)));
uut.methodUnderTest(d);
}
TEST(X, Fail)
{
Mock m;
Data d;
ClassUnderTest uut {&m};
EXPECT_CALL(m, foo(::testing::Ref(d)));
uut.methodThatCopies(d);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}