使用 GMock 的具有命名空间的模拟方法

Mock method with namespace using GMock

本文关键字:模拟 方法 命名空间 GMock 使用      更新时间:2023-10-16

我正在使用 GMock/Gtest 编写单元测试C++。我无法模拟命名空间中的方法。例如: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)无法使用上面的模拟函数调用。

尝试的步骤:

  1. 在期望类中添加了命名空间声明EXPECT_CALL(mock, corona::func1(_));->编译失败。
  2. 在模拟类中添加了命名空间声明MOCK_METHOD1(corona::func1, bool(string));->编译失败
  3. 在模拟类和测试类中使用命名空间做了不同的解决方法。

我被困在这一点上,无法对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);
}