Gmock简单使用


参考:https://blog.csdn.net/primeprime/article/details/99677794

#include "gtest.h"
#include "gmock.h"
#include <string>
#include 
using namespace std;
using namespace testing;

class Student {
public:
    virtual ~Student() {};
    virtual int GetAge(string name) = 0;
    // 测试接口
    virtual string GetName() = 0;
};

class MockStudent : public Student {
public:
    // MOCK_METHOD1(GetAge, int(string name));
    MOCK_METHOD(int, GetAge, (string name), (override));
    // 需要打桩测试的接口
    MOCK_METHOD0(GetName, string());
};

TEST(MockStudent, test_0)
{
    cout << "func begin: " << __func__ << endl;
    MockStudent zhang;
    EXPECT_CALL(zhang, GetAge(_))
        .Times(::testing::AtLeast(3))
        .WillOnce(::testing::Return(18))
        .WillRepeatedly(::testing::Return(19));
    cout << "1. " << zhang.GetAge("Test") << endl;
    cout << "2. " << zhang.GetAge("Test") << endl;
    cout << "3. " << zhang.GetAge("Test") << endl;
    cout << "4. " << zhang.GetAge("Test") << endl;
    cout << "5. " << zhang.GetAge("Test") << endl;
    cout << "func end:" << __func__ << endl;
}

TEST(MockStudent, test_1)
{
    cout << "func begin: " << __func__ << endl;
    MockStudent zhang;
    EXPECT_CALL(zhang, GetName)
        .Times(::testing::AtLeast(3))
        .WillOnce(::testing::Return("Ai"))
        .WillRepeatedly(::testing::Return("hello"));
    cout << "1. " << zhang.GetName() << endl;
    cout << "2. " << zhang.GetName() << endl;
    cout << "3. " << zhang.GetName() << endl;
    cout << "4. " << zhang.GetName() << endl;
    cout << "5. " << zhang.GetName() << endl;
    cout << "func end:" << __func__ << endl;
}

输出结果:

func begin: TestBody
1. 18
2. 19
3. 19
4. 19
5. 19
func end:TestBody
func begin: TestBody
1. Ai
2. hello
3. hello
4. hello
5. hello
func end:TestBody