关于C#:使用GMock命名空间的模拟方法

Mock method with namespace using GMock

我正在C中使用GMock / Gtest编写单元测试。我无法在命名空间中模拟方法。例如:被调用函数中的namespace::method_name()

示例代码:

1
2
3
4
5
6
TestClass.cc.  // Unit test class
TEST(testFixture, testMethod) {
   MockClass mock;
   EXPECT_CALL(mock, func1(_));
   mock.helloWorld();
}
1
2
3
4
MockClass.cc  // Mock class
class MockClass{
MOCK_METHOD1(func1, bool(string));
}
1
2
3
4
5
6
7
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方法进行单元测试。实际的源代码更加复杂。我该怎么办?


    您不能模拟免费功能,必须创建接口:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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);
    }

    并测试:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class MockClass : public Interface {
        MOCK_METHOD1(func1, bool(string));
    };

    TEST(testFixture, testMethod) {
       MockClass mock;
       EXPECT_CALL(mock, func1(_));

       helloWorld(mock);
    }