This week I'm going to learn GoogleTest for c++. I used JUnit frequently during my Java days. But never used a unit test framework (or unit tests) for embedded development.
Goals for the first days, done in Try out GoogleTest
- able to run a GoogleTest
- build a CMake script that does everything
- integrate with VSCode
and, in this post
- test some custom code: a class in a C++ module
Class interface
// test_module_interface.cpp
module;
#include <string_view>
export module test_module;
export namespace test_module {
class TestClass {
public:
bool match(const std::string_view& sv);
};
} // namespace test_module
Class implementation
// test_module_impl.cpp
module;
#include <string_view>
module test_module;
namespace test_module {
bool TestClass::match(const std::string_view& sv) {
using std::operator""sv;
return ("match"sv.compare(sv) == 0);
}
} // namespace test_module
Test Suite
// test_suite.cpp
#include <gtest/gtest.h>
import test_module;
TEST(string_view, match) {
test_module::TestClass o;
EXPECT_TRUE(o.match("match")); // should pass
}
TEST(string_view, missmatch) {
test_module::TestClass o;
EXPECT_FALSE(o.match("mismatch")); // should pass
}
CMake script
cmake_minimum_required(VERSION 3.28)
project(test_class_module C CXX ASM)
# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fmodules-ts")
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(${CMAKE_PROJECT_NAME})
target_sources(${CMAKE_PROJECT_NAME}
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/test_suite.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test_module_impl.cpp
)
target_sources(${CMAKE_PROJECT_NAME}
PRIVATE
FILE_SET cxx_modules TYPE CXX_MODULES FILES
${CMAKE_CURRENT_SOURCE_DIR}/test_module_iface.cpp
)
target_link_libraries( ${CMAKE_PROJECT_NAME}
PRIVATE
GTest::gtest_main
)
include(GoogleTest)
gtest_discover_tests(${CMAKE_PROJECT_NAME})
Result

link to all posts.