1. 下载googletest源码
git clone https://github.com/google/googletest.git
2. 编译googletest
cd googletest
mkdir build
cd build
cmake ..
make -j8
3. 安装到系统中
make install
4. 创建工程,结构如下
4.1 主目录中的CMakeLists.txt
project(Shape)
cmake_minimum_required(VERSION 3.13)
enable_testing()
add_compile_options(-std=c++11)
add_subdirectory(src)
add_subdirectory(tests)
4.2 src目录中的CMakeLists.txt
add_library(shape SHARED shape.cpp)
add_executable(app main.cpp)
target_link_libraries(app shape)
4.3 src目录中的shape.h
#ifndef _SHAPE_H_
#define _SHAPE_H_
class Shape
{
public:
virtual void draw() = 0;
};
class Point : public Shape
{
public:
Point(int x, int y);
void setX(int x);
int x() const;
void setY(int y);
int y() const;
virtual void draw() override;
private:
int m_x;
int m_y;
};
#endif //_SHAPE_H_
4.4 src目录中shape.cpp
#include <iostream>
#include "shape.h"
Point::Point(int x, int y)
: m_x(x)
, m_y(y)
{
}
void Point::setX(int x)
{
m_x = x;
}
int Point::x() const
{
return m_x;
}
void Point::setY(int y)
{
m_y = y;
}
int Point::y() const
{
return m_y;
}
void Point::draw()
{
std::cout << "draw: " << m_x << ", " << m_y << std::endl;
}
4.5 src目录中main.cpp
#include <iostream>
#include "shape.h"
int main(int argc, char *argv[])
{
Point point(100, 200);
point.draw();
return EXIT_SUCCESS;
}
4.6 tests目录中CMakeLists.txt
include_directories(${CMAKE_SOURCE_DIR}/src)
add_executable(autotest test_main.cpp)
target_link_libraries(autotest pthread gmock gmock_main gtest gtest_main shape)
add_test(NAME autotest COMMAND ${EXECUTABLE_OUTPUT_PATH}/autotest)
4.7 tests目录中test_main.cpp
#include <gtest/gtest.h>
#include "shape.h"
TEST(Shape, shape)
{
const int x = 100;
const int y = 200;
Point point(x, y);
EXPECT_EQ(x, point.x());
EXPECT_EQ(y, point.y());
}
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
5. 编译
mkdir build
cd build
cmake ..
make -j8
6. 执行主程序
./src/app
程序输出如下:
draw: 100, 200
7. 执行单元测试
make test
程序输出如下:
Running tests...
Test project /home/avery/Workspace/deepin/shape/build
Start 1: autotest
1/1 Test #1: autotest ......................... Passed 0.00 sec
100% tests passed, 0 tests failed out of 1
Total Test time (real) = 0.00 sec
或者执行
./tests/autotest
程序输出如下:
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from Shape
[ RUN ] Shape.shape
[ OK ] Shape.shape (0 ms)
[----------] 1 test from Shape (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
8. 本示例下载源码
https://download.csdn.net/download/axylp123/86506234