Mock method with namespace using GMock
我正在C中使用GMock / Gtest编写单元测试。我无法在命名空间中模拟方法。例如:被调用函数中的
示例代码:
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 } } |
在上面的
尝试的步骤:
我现在被困住了,无法对
您不能模拟免费功能,必须创建接口:
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); } |