纯虚拟类
class ConfigGetter {
public:
virtual const std::string Get(const char *name,
const char *default_value) const = 0;
};
模拟
class MockConfigGetter : public engine::ConfigGetter {
public:
MOCK_CONST_METHOD2(Get, const std::string(const char *, const char *));
};
测试用例
TEST(ConfigTest, NormalString) {
NiceMock<MockConfigGetter> getter;
EXPECT_CALL(getter, Get("SERVER_LISTEN_PORT", ""))
.WillRepeatedly(Return("80"));
// Pass
ASSERT_EQ("80", getter.Get("SERVER_LISTEN_PORT", ""));
// GetNewConfig internal call getter->Get("SERVER_LISTEN_PORT", "")
auto f = engine::GetNewConfig(&getter);
ASSERT_NE(f, nullptr);
// Failure
ASSERT_EQ(80, f->listen_port);
}
好的模拟报告:
Unexpected mock function call - returning default value.
Function call: Get(0x556fb6ea4860 pointing to "SERVER_LISTEN_PORT", 0x556fb6ea4843 pointing to "")
Returns: ""
Google Mock tried the following 1 expectation, but it didn't match:
/home/phillip/projects/engine-test/src/config/config-test.cpp:26: EXPECT_CALL(getter, Get("SERVER_LISTEN_PORT", ""))...
Expected arg #0: is equal to 0x556fb6ea2878 pointing to "SERVER_LISTEN_PORT"
Actual: 0x556fb6ea4860 pointing to "SERVER_LISTEN_PORT"
Expected arg #1: is equal to 0x556fb6ea27bc pointing to ""
Actual: 0x556fb6ea4843 pointing to ""
Expected: to be called any number of times
Actual: called twice - satisfied and active
arg0和arg1与EXPECT_CALL完全相同。我不知道为什么第二个电话不匹配。
答案 0 :(得分:2)
之所以会这样,是因为gmock比较了参数(即指针)的值。要比较字符串,您需要添加相应的匹配项,即
EXPECT_CALL(getter, Get(StrEq("SERVER_LISTEN_PORT"), StrEq("")))
.WillRepeatedly(Return("80"));