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

标签 c++ unit-testing namespaces googletest googlemock

我正在使用 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)无法使用上述模拟函数进行调用。

尝试的步骤:
  • 在 EXPECT CLASS 中添加了命名空间声明EXPECT_CALL(mock, corona::func1(_)); -> 编译失败。
  • 在 Mock 类中添加命名空间声明MOCK_METHOD1(corona::func1, bool(string)); -> 编译失败
  • 在模拟类和测试类中使用命名空间做了不同的解决方案。

  • 我被困在这一点上,无法对 helloWorld 进行单元测试方法。实际的源代码更复杂。我怎么能这样做?

    最佳答案

    你不能模拟自由函数,你必须创建接口(interface):

    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);
    }
    

    关于c++ - 使用 GMock 的具有命名空间的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61942572/

    相关文章:

    c++ - 分段故障(核心已转储)-二维数组

    c++ - 正则表达式 - 将所有内容与末尾的数字匹配

    ruby - 我可以模拟 RSpec double 的类名吗?

    java - JUnit @AfterClass 运行时被添加到一个糟糕的测试用例 :(

    c++ - calloc 的等效代码

    c++ - 相当于 inet_aton 的窗口

    c# - 使用在代码体中声明的具体类的单元测试类

    ruby-on-rails - Ruby on Rails,重命名模型后未初始化的常量

    Chicken Scheme 中的命名空间

    javascript - 用函数包装 jQuery 插件