我正在尝试使用googletest设置CMake C ++项目。我不是很了解CMake并使用this指南来创建我自己的设置。
尝试构建项目时,编译器会抛出错误:
.../test.cpp:12:5: error: ‘EXPECT_THAT’ was not declared in this scope
EXPECT_THAT(a, ContainerEq(b));
^~~~~~~~~~~
.../test.cpp:12:5: note: suggested alternative: ‘EXPECT_GT’
EXPECT_THAT(a, ContainerEq(b));
^~~~~~~~~~~
EXPECT_GT
../test.cpp:13:31: error: ‘ContainerEq’ is not a member of ‘testing’
EXPECT_THAT(a, ::testing::ContainerEq(b)); // doesn't work either
GTest的部分似乎工作得很好。如果我评论第二次测试,一切正常。
文件夹结构:
Toplevel CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
project (TestProject)
enable_testing()
add_subdirectory(test)
测试/的CMakeLists.txt
include(gtest.cmake)
add_executable(UnitTests test.cpp)
target_link_libraries(UnitTests libgtest)
add_test(NAME AllUnitTests COMMAND UnitTests)
测试/ gtest.cmake
find_package(Threads REQUIRED)
# Enable ExternalProject CMake module
include(ExternalProject)
# Download and install GoogleTest
ExternalProject_Add(
gtest
URL https://github.com/google/googletest/archive/master.zip
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/gtest
# Disable install step
INSTALL_COMMAND ""
)
# Get GTest source and binary directories from CMake project
ExternalProject_Get_Property(gtest source_dir binary_dir)
# Create a libgtest target to be used as a dependency by test programs
add_library(libgtest IMPORTED STATIC GLOBAL)
add_dependencies(libgtest gtest)
# Set libgtest properties
set_target_properties(libgtest PROPERTIES
"IMPORTED_LOCATION" "${binary_dir}/googlemock/gtest/libgtest.a"
"IMPORTED_LINK_INTERFACE_LIBRARIES" "${CMAKE_THREAD_LIBS_INIT}"
)
# Create a libgmock target to be used as a dependency by test programs
add_library(libgmock IMPORTED STATIC GLOBAL)
add_dependencies(libgmock gtest)
# Set libgmock properties
set_target_properties(libgmock PROPERTIES
"IMPORTED_LOCATION" "${binary_dir}/googlemock/libgmock.a"
"IMPORTED_LINK_INTERFACE_LIBRARIES" "${CMAKE_THREAD_LIBS_INIT}"
)
# I couldn't make it work with INTERFACE_INCLUDE_DIRECTORIES
include_directories("${source_dir}/googletest/include"
"${source_dir}/googlemock/include")
测试/ TEST.CPP
#include <vector>
#include "gtest/gtest.h"
TEST(SampleTest, Equal){
EXPECT_EQ(42, 42);
}
TEST(ContainerComparison, Equal){
const std::vector<int> a(2, 1);
const std::vector<int> b(2, 1);
EXPECT_THAT(a, ContainerEq(b));
EXPECT_THAT(a, ::testing::ContainerEq(b)); // doesn't work either
}
int main(int argc, char** argv){
::testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
return ret;
}
答案 0 :(得分:1)
Matchers are a part of GMock。你需要包含它(并链接到它的库)。
#include <gmock/gmock.h>
GMock曾经是一个独立的库,现在是merged into GoogleTest repository。但它有单独的包含和库。
您关注的教程是从2014年开始的。您可以在GoogleTest GitHub repo找到体面的最新教程。