其他评论和回答建议您使用
add_test()
。如果您想要使用CMake的CTest框架的便利性,则只需要使用
enable_testing()
和
add_test()
。如果您希望将任何可执行文件作为测试程序,那么您可以使用这两个函数。让我们深入研究您的问题。
首先,简化问题。我假设您已经成功构建了Google Test,并知道如何使用它(如果不知道,那是另一个问题)。简化您的
CMakeLists.txt
文件。
CMakeLists.txt
cmake_minimum_required(VERSION 3.7)
project(expirement)
find_package(Threads REQUIRED)
set(CMAKE_CXX_STANDARD 14)
set(SOURCE_FILES main.cpp getstring.cpp tests.cpp)
include_directories($ENV{HOME}/googletest/googletest/include)
add_executable(expirement main.cpp getstring.cpp tests.cpp)
target_link_libraries(expirement
$ENV{HOME}/googletest/googlemock/gtest/libgtest.a
$ENV{HOME}/googletest/googlemock/gtest/libgtest_main.a
)
target_link_libraries(expirement Threads::Threads)
你会注意到我去掉了ExternalProject
部分,你可以找出我放置了googletest的位置。
现在,由于我们没有你的源代码,我不得不模拟一些存根。
main.cpp
#include "gtest/gtest.h"
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
getstring.h
std::string GetTheString()
getstring.cpp
#include <string>
std::string GetTheString() {
return (std::string) "asdfasf";
}
现在,使用
cmake
进行构建:
~/foo
❯ cmake .
-- The C compiler identification is AppleClang 8.1.0.8020038
-- The CXX compiler identification is AppleClang 8.1.0.8020038
-- Check for working C compiler: /App
[ ... cmake output goes here. blah blah blah ... ]
-- Found Threads: TRUE
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/nega/foo
~/foo
❯ make
Scanning dependencies of target expirement
[ 25%] Building CXX object CMakeFiles/expirement.dir/main.cpp.o
[ 50%] Building CXX object CMakeFiles/expirement.dir/getstring.cpp.o
[ 75%] Building CXX object CMakeFiles/expirement.dir/tests.cpp.o
[100%] Linking CXX executable expirement
[100%] Built target expirement
~/foo
❯
现在运行实验,但是要简化。 (还要记得转义那些 * !)
~/foo
❯ ./expirement --gtest_filter='*'
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from StringTest
[ RUN ] StringTest.CheckReturnValue
[ OK ] StringTest.CheckReturnValue (0 ms)
[----------] 1 test from StringTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 1 test.
~/foo
❯
如果您能够到达这个点,太棒了!您已经走得很远了。您可以为
--gtest_filter
构建更严格的过滤器。(记得转义那些 *!)您可以构建您的
CMakeLists.txt
以包含那些
ExternalProject
部分,您可以将其取出。不过,请记住,
ExternalProject
的真正强大和实用性在于当您希望构建外部项目作为您的项目的构建过程的一部分时。通常情况下,更简单的方法是指导用户自己下载并构建该外部项目。
如果您没有到达这个点,请停止。退后一步,并查看您的代码。确保您正确设置并定义了测试。确保您正确初始化了googletest。确保您的测试名称中没有任何拼写错误(这是一个常见的“陷阱”)。修复这一部分之后,再回到CMake部分。
CMakeLists.txt
文件没有创建测试,experiment
只是一个可执行文件。 - Tsyvarev