GTest + vscode 实现 C++ 单元测试
本文将介绍如何以源码的形式在 vscode 中使用 googletest,重点在于目录结构与 CMakeLists.txt
的创建,不涉及如何在 vscode 中使用 CMake 进行构建与生成。目标是将生产代码与测试代码分离,保持代码环境整洁。
创建项目 gtestVscodeEx
,目录结构如下:
gtestVscodeEx
│ CMakeLists.txt
│
└───include
│ │ test.h
│
└───src
│ │ main.cpp
│ │ test.cpp
│
└───tests
│ │ googletest-master
│ │ CMakeLists.txt
│ │ test0.cpp
上述 include
与 src
中为生产代码,tests
中为测试代码与 gtest 源码。
其中,test.h
内容如下:
#include <iostream>
class TestClass
{
private:
int var;
public:
TestClass();
~TestClass();
int GetVar();
};
test.cpp
内容如下:
#include "test.h"
TestClass::TestClass()
{
var = 1;
}
TestClass::~TestClass()
{
}
int TestClass::GetVar()
{
return var;
}
单元测试 test0.cpp
内容如下:
#include "test.h"
#include "gtest/gtest.h"
TEST(TESTCASE, test0)
{
EXPECT_EQ(0, 0);
EXPECT_EQ("a", "a");
}
TEST(TESTCASE, test1)
{
TestClass tmp;
EXPECT_EQ(1, tmp.GetVar());
}
主目录下的 CMakeLists.txt
内容如下:
# cmake version require
cmake_minimum_required(VERSION 3.0.0)
# assign cpp standard
set(CMAKE_CXX_COMPILER "c++")
set(CMAKE_CXX_FLAGS "-std=c++11")
# set project name and version
project(gtestTest VERSION 0.1.0)
# add include and src path
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src)
# file to compile
add_executable(${PROJECT_NAME} src/main.cpp)
# add cpp as lib
add_library(libTest src/test.cpp)
# for gtest, included in tests sub-folder
enable_testing()
add_subdirectory(tests)
tests/CMakeLists.txt
的内容如下:
include(CTest)
# set test build target name
set(TEST_BINARY ${PROJECT_NAME}_test)
# add new test
add_executable(${TEST_BINARY} test0.cpp)
# add googletest subdirectory
add_subdirectory(googletest-master)
# this is so we can #include <gtest/gtest.h>
include_directories(googletest-master/include)
add_test(test_1 tests/test0.cpp)
# link libraries to use in this executable
# link gtest_main to avoid your own main.cpp
target_link_libraries(${TEST_BINARY} PUBLIC libTest gtest gtest_main)
按照此结构可以分离单元测试代码与生产代码,保持代码环境整洁,有助于实践 TDD。