使用GMock的命名空间的Mock方法

问题描述 投票:0回答:1

我正在使用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函数调用。

尝试了一些步骤。

  1. 在EXPECT CLASS中添加了命名空间声明EXPECT_CALL(mock, corona::func1(_)); -> 编译失败。
  2. 在Mock类中添加了命名空间声明。MOCK_METHOD1(corona::func1, bool(string)); -> 编译失败
  3. 在mock类和测试类中使用namespace做了不同的变通方案。

我卡在这一点上,无法对 helloWorld 方法。实际源码比较复杂。如何才能做到这一点?

c++ unit-testing namespaces googletest gmock
1个回答
2
投票

你不能模拟自由函数,你必须创建接口。

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.