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

Mock method with namespace using GMock

我正在使用 C++ 中的 GMock/Gtest 编写单元测试。我无法模拟命名空间中的方法。例如:被调用函数中的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 中添加命名空间声明 CLASS EXPECT_CALL(mock, corona::func1(_)); -> 编译失败。
  2. 在 Mock 中添加了命名空间声明 class MOCK_METHOD1(corona::func1, bool(string)); -> 编译失败
  3. 在模拟 class 和测试 class 中使用命名空间是否有不同的变通解决方案。

我卡在了这里,无法对 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);
}