Skip to content

Test with GoogleTest

cmake
cmake_minimum_required(VERSION 3.14)
project(my_project)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

enable_testing()

add_executable(hello_test hello_test.cpp)
target_link_libraries(hello_test GTest::gtest_main)

include(GoogleTest)
gtest_discover_tests(hello_test)
cpp
#include "greet.hpp"
#include <string>
std::string greet(std::string name) { return "Hello " + name + "!"; }
cpp
#include <string>
std::string greet(std::string name);
cpp
#include "greet.hpp"
#include <gtest/gtest.h>

// Demonstrate some basic assertions.
TEST(HelloTest, BasicAssertions) {
  // Expect two strings not to be equal.
  EXPECT_STRNE("hello", "world");
  // Expect equality.
  EXPECT_EQ(7 * 6, 42);
}

TEST(GreetTest, GreetWithName) {
  EXPECT_EQ(greet("Alice"), "Hello Alice!");
  EXPECT_EQ(greet("Alan Turing"), "Hello Alan Turing!");
}
sh
cmake -B build
cmake --build build
(cd build && ctest)

https://google.github.io/googletest/