编译与安装
请参考下面的链接
https://blog.csdn.net/wei242425445/article/details/87968490
代码目录结构
wilson@ubuntu:~/code/cpp/test_gtest$ tree
├── build
├── CMakeLists.txt
├── Func
│ ├── Calc.cpp
│ ├── Calc.h
│ ├── TestCalc.cpp
│ ├── TestCalc.h
│ └── TestGlobalCalc.cpp
└── Main.cpp
CMakeLists.txt的编写
cmake_minimum_required(VERSION 2.8)
project(demo)
SET(CMAKE_BUILD_TYPE "Debug")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread -g -Wall")
SET(GTESTLIB /usr/local/lib/libgtest.a)
aux_source_directory(. DIRSRCS)
aux_source_directory(Func/. FUNCSRCS)
include_directories(Func)
add_executable(demo ${DIRSRCS} ${FUNCSRCS})
target_link_libraries(demo ${GTESTLIB})
- 编译选项需要带着-pthread
- 需要关联/usr/local/lib/libgtest.a
Main.cpp的编写
初始化googletest然后运行所有的测试即可
#include <iostream>
#include "gtest/gtest.h"
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
全局测试用例
参数1是指用例属于哪里的,参数2是指用例名称
// TestGlobalCalc.cpp
#include "Calc.h"
#include "gtest/gtest.h"
// This test is named "EqualT", and belongs to the "FucTest"
TEST(FucTest, EqualT)
{
func::Calc cal;
EXPECT_EQ(1, 1);
EXPECT_GT(2, 1);
EXPECT_TRUE(cal.IsTrue());
//EXPECT_FALSE(cal.IsTrue());
//EXPECT_STREQ(nullptr, "asda");
}
单元测试用例
TestCalc.h
可以继承testing::Test的启动和结束的接口
#pragma once
#include "Calc.h"
#include "gtest/gtest.h"
namespace func
{
class TestCalc : public testing::Test
{
private:
void SetUp() override;
void TearDown() override;
};
}
TestCalc.cpp
如果需要编写类的测试用例,需要使用TEST_F
#include "TestCalc.h"
namespace func
{
void TestCalc::SetUp()
{
std::cout << "set up..." << std::endl;
}
void TestCalc::TearDown()
{
std::cout << "tear down..." << std::endl;
}
TEST_F(TestCalc, test1)
{
EXPECT_EQ(1, 1);
}
} // namespace func