我在将googletest集成到我的现有项目中遇到了麻烦。我创建了一个简单的项目来表示我的项目结构:
项目结构
CMakeLists.txt:
cmake_minimum_required(VERSION 3.13)
project(TestTester)
set(CMAKE_CXX_STANDARD 14)
include_directories(existing_source)
add_subdirectory(existing_source)
add_subdirectory(new_test_source)
existing_source/CMakeLists.txt:
cmake_minimum_required(VERSION 3.13)
project(Test_TestTester)
set(CMAKE_CXX_STANDARD 14)
add_executable(TestTester main.cpp existing.h)
new_test_source/CMakeLists.txt:
cmake_minimum_required(VERSION 3.13)
project(Test_TestTester)
set(CMAKE_CXX_STANDARD 14)
find_package(PkgConfig REQUIRED)
pkg_check_modules(gtest REQUIRED gtest>=1.8.1)
SET(CMAKE_CXX_FLAGS -pthread)
enable_testing()
include_directories(${gtest_INCLUDE_DIRS})
add_executable(Test_TestTester main_test.cpp ../existing_source/existing.h)
target_link_libraries(Test_TestTester ${gtest_LIBRARIES})
add_test(NAME Test COMMAND Test_TestTester)
existing_source/existing.h
#ifndef TESTTESTER_EXISTING_H
#define TESTTESTER_EXISTING_H
int sample() {
return 1;
}
#endif //TESTTESTER_EXISTING_H
existing_source/main.cpp
#include <iostream>
#include "existing.h"
int main() {
std::cout << "sample() output = " << sample() << std::endl;
return 0;
}
new_test_source/main_test.cpp
#include <gtest/gtest.h>
#include "../existing_source/existing.h"
TEST(SampleTestCase, TestOneIsOne) {
EXPECT_EQ(1, 1);
}
TEST(ExistingCodeTestCase, TestSample) {
EXPECT_EQ(1, sample());
}
GTEST_API_ int main(int argc, char **argv) {
printf("Running main() from %s\n", __FILE__);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
目标:
使用CMake构建将创建两个可执行文件,一个是TestTester,另一个名为Test_TestTester(很抱歉,这个名称看起来我本可以选择更好的项目名称!)。
TestTester将是主项目可执行文件,它将运行existing_course/main.cpp中的代码,并输出sample() output = 1
。
Test_TestTester应该是来自main_test.cpp的单元测试,测试1 == 1
和1 == sample()
。这应该在构建项目时运行。
尝试:
我尝试使用CMake的add_subdirectory()公开test子目录中具有其自己的add_executable()的第二个CMakeLists.txt,其中包含测试程序的名称,但我找不到与测试程序相关的任何输出。使用enable_testing()后跟add_test()也未能产生任何变化。
更新:
我意识到一些问题和假设是错误的。
- 在CLion中,默认情况下要构建特定目标。必须调用Build all (
cmake --build ... --target all
)来构建其他可执行文件。 - 我阅读的其他问题似乎与此不相关。在将其包含到项目中之前,我在计算机上编译并安装了googletest。
- 这可能不是一个问题,但看起来大多数人选择使用每个目录都有自己的CMakeLists.txt文件来组织他们的项目。我重新组织了我的项目以匹配,以便更容易遵循其他人的建议。
我用我的更改更新了CMakeLists文件。使用--target all
可以适当地构建所有内容,但我仍然无法在构建项目时运行测试。
sample
函数不应该至少有static
或static inline
吗? - KamilCuk