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:
- able to run a GoogleTest
- build a CMake script that does everything
- integrate with VSCode
The first 2 were very easy. I followed Quickstart: Building with CMake. It learns you to write a CMake file and a first test script.
My CMake file:
cmake_minimum_required(VERSION 3.28) project(test_gps_teseo CXX) # 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} test.cpp ) target_link_libraries( ${CMAKE_PROJECT_NAME} GTest::gtest_main ) include(GoogleTest) gtest_discover_tests(${CMAKE_PROJECT_NAME})
This file will prepare my project for testing. It 'll also download GoogleTest (if not cached).
The c++ test script is identical to the one in the tutorial. Just 2 assertions to see if things work.
#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); }
Toolchain: Even though my embedded code is currently running on a Pico, I took care that all "business logic" is platform independent. The embedded code that I want to test compiles and runs equally well on a Windows or Linux (e.g. Raspberry Pi) device. Since I run my test bed on a Windows machine, I'm using Windows C++ toolchain to build and execute the tests: the latest GCC W64 MINGW release.
At this point, I 'd be able to test this from a command line, but I used VSCode with the TestMate C++ extension.
The extension shows the available test cases (the one from the source file above, auto detected). And allows you to run them one time or continuous.
The status is shown visually. A green checkbox is success. A red X is failure. At the same time, the output is available:
If you already have the CMake extensions installed in VSCode: that also integrates with the test view and offers very similar functionality.
link to all posts.