C/C++教程

Gmock简单使用

本文主要是介绍Gmock简单使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

 

#include "gtest.h"
#include "gmock.h"
#include <string>
#include <iostream>
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

 

这篇关于Gmock简单使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!