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

被折叠的 条评论
为什么被折叠?



