CPP(c++) google gmock

Google Mock(简称gmock)是Google在2008年推出的一套针对C++的Mock框架

当我们在单元测试、模块的接口测试时,当这个模块需要依赖另外一个/几个类,而这时这些个类还没有开发好,
这时我们就可以定义了Mock对象来模拟那些类的行为。

建议直接参考: https://blog.csdn.net/Primeprime/article/details/99677794

#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <iostream>
#include <string>


namespace seamless {
    class FooInterface {  //FooInterface  函数getArbitraryString 还没开发好
    public:
        virtual ~FooInterface() {}
    public:
        virtual std::string getArbitraryString() = 0;
    };
}  // namespace seamless

namespace seamless {
    class MockFoo: public FooInterface { //Mock对象来模拟那些类的行为
    public:
        MOCK_METHOD0(getArbitraryString, std::string()); ///0 表示该函数没有参数,如果一个参数,则为1
    };
} 

using namespace seamless;
using namespace std;
 
using ::testing::Return;
 
int main(int argc, char** argv) {
        ::testing::InitGoogleMock(&argc, argv);// 初始化一个 Google Mock
        string value = "Hello World!";
        MockFoo mockFoo; // 生成mockFoo对象
        EXPECT_CALL(mockFoo, getArbitraryString()).Times(1).  //期望定义方程。注释如下
                WillOnce(Return(value));
        string returnValue = mockFoo.getArbitraryString();
        cout << "Returned Value: " << returnValue << endl;
 
        return EXIT_SUCCESS;
}

结果:Returned Value: Hello World!
原文地址:https://www.cnblogs.com/heimazaifei/p/12176771.html