我正在使用C++中的GMockGtest编写单元测试。我无法模拟一个命名空间中的方法。例如,在被调用的函数中。namespace::method_name()
在被调用的函数中
示例代码。
TestClass.cc. // Unit test class
TEST(testFixture, testMethod) {
MockClass mock;
EXPECT_CALL(mock, func1(_));
mock.helloWorld();
}
MockClass.cc // Mock class
class MockClass{
MOCK_METHOD1(func1, bool(string));
}
HelloWorld.cc // Main class
void helloWorld() {
string str;
if (corona::func1(str)) { -> function to be mocked
// Actions
}
}
在上面的 helloWorld
方法。corona::func1(str)
无法使用上述mock函数调用。
尝试了一些步骤。
EXPECT_CALL(mock, corona::func1(_));
-> 编译失败。MOCK_METHOD1(corona::func1, bool(string));
-> 编译失败我卡在这一点上,无法对 helloWorld
方法。实际源码比较复杂。如何才能做到这一点?
你不能模拟自由函数,你必须创建接口。
struct Interface
{
virtual ~Interface() = default;
virtual bool func1(const std::string&) = 0;
};
struct Implementation : Interface
{
bool func1(const std::string& s) override { corona::func1(s); }
};
void helloWorld(Interface& interface) {
string str;
if (interface.func1(str)) { // -> function to be mocked
// Actions
}
}
// Possibly, helper for production
void helloWorld()
{
Implementation impl;
helloWorld(impl);
}
和测试。
class MockClass : public Interface {
MOCK_METHOD1(func1, bool(string));
};
TEST(testFixture, testMethod) {
MockClass mock;
EXPECT_CALL(mock, func1(_));
helloWorld(mock);
}