<gtest/gmock> 编译安装

本文详细介绍如何从官网下载并安装Google Test框架至指定目录,包括解压、创建编译及安装目录等步骤。此外,还提供了一个具体的单元测试案例,演示如何利用该框架进行C++代码的单元测试。

1 下载
从官网https://github.com/google/googletest/releases
下载,如googletest-1.10.x.zip

2 解压到一个目录
unzip googletest-1.10.x.zip

3 创建编译目录
mkdir googletest-1.10.x_building

4 创建安装目录
mkdir googletest-1.10.x_build

5 进入编译目录
cd googletest-1.10.x_building
cmake …/googletest-1.10.x -DCMAKE_INSTALL_PREFIX=/root/googletest-1.10.x_build

6 编译和安装
make
make install
这样就会自动安装到指定目录/root/googletest-1.10.x_build

7 查看安装目录
cd …
tree googletest-1.10.x_build

8 设置LD_LIBRARY_PATH
由于默认编译为静态库,所以不需要设置动态链接库的路径

9 编写测试文件
FooInterface.h

#ifndef FOOINTERFACE_H_
#define FOOINTERFACE_H_

#include <string>

namespace seamless {

        class FooInterface {
                public:
                        virtual ~FooInterface() {}

                public:
                        virtual std::string getArbitraryString() = 0;
        };  

}  // namespace seamless

#endif // FOOINTERFACE_H_

FooMock.h

#ifndef MOCKFOO_H_
#define MOCKFOO_H_

#include <gmock/gmock.h>
#include <string>
#include "FooInterface.h"

namespace seamless {

        class MockFoo: public FooInterface {
                public:
                        MOCK_METHOD0(getArbitraryString, std::string());
        };  

}  // namespace seamless

#endif // MOCKFOO_H_

FooMain.cc

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

#include "FooMock.h"

using namespace seamless;
using namespace std;

using ::testing::Return;

int main(int argc, char** argv) {
        ::testing::InitGoogleMock(&argc, argv);

        string value = "Hello World";
        MockFoo mockFoo;
        EXPECT_CALL(mockFoo, getArbitraryString()).Times(1).
                WillOnce(Return(value));
        string returnValue = mockFoo.getArbitraryString();
        cout << "Returned Value: " << returnValue << endl;

        return EXIT_SUCCESS;
}

10 编译
g++ FooMain.cc -lgtest -lgmock -lpthread -std=c++11 -I/root/googletest-1.10.x_build/include -L/root/googletest-1.10.x_build/lib64

11 执行
[root@localhost 10_gtest_mock]# ./a.out
Returned Value: Hello World
执行成功。

参考:
1 文中测试程序参考了https://www.cnblogs.com/welkinwalker/archive/2011/11/29/2267225.html 中的一个例子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值