【发布时间】:2019-12-09 21:21:06
【问题描述】:
我正在尝试将正常编译和带有 gtest 的单元测试集成到一个 cmake 文件中,但我不知道如何实现这一点。这是我的项目:
|---include
| |---Student.h
|
|---src
| |---Student.cpp
| |---main.cpp
|
|---unittest
| |---TestStudent.cpp
|
|---CMakeLists.txt # how to write this file?
所以Student.h、Student.cpp和main.cpp是源代码,TestStudent.cpp是测试代码,其中包括gtest/gtest.h和一个main函数,这里是:
#include "gtest/gtest.h"
#include "Student.h"
class TestStudent : public ::testing::Test
{
protected:
Student *ps;
void SetUp() override
{
ps = new Student(2, "toto");
}
void TearDown() override
{
delete ps;
}
};
TEST_F(TestStudent, ID)
{
EXPECT_TRUE(ps->GetID() == 2);
EXPECT_TRUE(ps->GetName() == "toto");
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
现在,如果我想编译源代码,我需要运行g++ -std=c++11 Student.cpp main.cpp -o a.out,而如果我想编译测试代码,我需要运行g++ -std=c++11 TestStudent.cpp Student.cpp -lgtest -lpthread -o test.out。
那么,我该如何编写CMakeLists.txt 来让我编译不同的目标,例如cmake NORMAL 和cmake TEST?
【问题讨论】:
-
您添加两个可执行目标,每个可执行文件一个。然后 CMake 将使用这两个目标创建一个
Makefile(或项目),以便您可以分别构建它们。 -
@Someprogrammerdude 你能给我看一个非常简单的例子吗?
-
你知道 CMake
add_exectuable命令吗?您可以在单个CMakeLists.txt中拥有任意数量的add_executable命令。
标签: c++ unit-testing c++11 cmake