Module 8 · Lesson 64 of 90

GoogleTest basics and parameterized tests

Verify a state machine on the host with GoogleTest: AAA tests, fixtures, EXPECT versus ASSERT, and parameterized and typed test tables.

  • Beginner to advanced
  • 12 min read
  • 35 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM; g++ (GCC 13); cmake; the libgtest-dev package from apt

Your place in the module
By the end you can 4 objectives
  • Write TEST and TEST_F cases that follow the Arrange, Act, Assert pattern
  • Choose between EXPECT_* and ASSERT_* correctly, including inside helper functions
  • Drive a state machine transition table with TEST_P and INSTANTIATE_TEST_SUITE_P
  • Write TYPED_TEST cases that check one class template across several types
Video coming soonGoogleTest basics and parameterized tests
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Active objects and queued commands
  • An active object is a thread plus a message queue: callers post commands and return immediately, and the worker executes them serially.
  • The command pattern turns a request into an object, which is what makes queuing, deferring and retrying possible.
  • Virtual interfaces keep one copy of client code and allow run-time substitution; templates devirtualize and inline but emit one copy per type.
01

Unit tests and the AAA pattern

5 min read

In the last lesson active objects queued commands for the ara-lite middleware. This lesson proves the code works: the AAA pattern, TEST and TEST_F, EXPECT versus ASSERT, and parameterized and typed tests over a state machine.

A runs on the development host, not on the board. That split is the heart of embedded testing. The heater controller in this lesson is plain C++: it compiles with g++ on Ubuntu 24.04 exactly as it does for the Raspberry Pi, and a full run of its tests takes milliseconds. Only the code that touches GPIO needs real hardware, and the next lesson, GoogleMock and test doubles for hardware, shows how to replace that code with fakes so the logic stays testable on the host. When tests are this cheap you run them after every edit, and they start shaping the design: code that is hard to test usually has hidden dependencies.

The running example is the heater controller from the state machine lesson: three states (Idle, Heating, Fault), four events (Start, Stop, Overtemp, Reset), and entry and exit actions on Heating. To make the actions observable without hardware, the class counts them instead of driving a pin.

Heater controller under testIdleHeatingFaultTransitionsStartIdleHeatingStopHeatingIdleOvertempHeatingFaultResetFaultIdleIdleHeatingFaultTransitionsStartIdleHeatingStopHeatingIdleOvertempHeatingFaultResetFaultIdle
The heater controller under test: four legal transitions; every other event is ignored
cpp
enum class State { Idle, Heating, Fault };
enum class Event { Start, Stop, Overtemp, Reset };

class Heater {
public:
    explicit Heater(State initial = State::Idle) : state_{initial} {}
    void handle(Event e);
    State state() const { return state_; }
    int heating_entries() const { return entries_; }
    int heating_exits() const { return exits_; }
private:
    State state_;
    int entries_ = 0;
    int exits_ = 0;
};
cpp
void Heater::handle(Event e) {
    State next = state_;
    switch (state_) {
    case State::Idle:
        if (e == Event::Start) next = State::Heating;
        break;
    case State::Heating:
        if (e == Event::Stop)     next = State::Idle;
        if (e == Event::Overtemp) next = State::Fault;
        break;
    case State::Fault:
        if (e == Event::Reset) next = State::Idle;
        break;
    }
    if (next == state_) return;  // ignored event: no actions run
    if (state_ == State::Heating) ++exits_;  // exit action first
    if (next   == State::Heating) ++entries_;  // then entry action
    state_ = next;
}

Two details matter for the tests you will write. An ignored event returns early: no exit action, no entry action, no counter change. And on a real transition the exit action of the old state runs before the entry action of the new one, which is exactly the ordering a test should pin down.

Every test body follows the . Arrange constructs the object and puts it in the state the test needs. Act calls the one function under test. Assert compares what happened with what should have happened. Keeping the phases separate makes a failure readable: you know which single action broke which expectation.

cpp
#include <gtest/gtest.h>
#include "heater.hpp"

TEST(HeaterSm, StartsIdle) {
    Heater h;                              // Arrange
    EXPECT_EQ(h.state(), State::Idle);     // Assert (no Act needed)
}

TEST(HeaterSm, StartMovesToHeating) {
    Heater h;                              // Arrange
    h.handle(Event::Start);                // Act
    EXPECT_EQ(h.state(), State::Heating);  // Assert
}

The TEST macro takes a suite name and a test name. It expands into a class with a TestBody() method and registers it in a global registry at static initialization time, so you never call the test yourself. The suite name groups related tests; the full name HeaterSm.StartMovesToHeating is what the runner prints and what --gtest_filter matches. Name tests as sentences about behaviour, one behaviour per test, so a failure report reads like a bug description.

You do not write main. On Ubuntu 24.04 the apt package libgtest-dev ships the headers and prebuilt static libraries, and libgtest_main provides a main that initializes GoogleTest and calls RUN_ALL_TESTS(). GoogleTest uses POSIX threads internally, so link with -pthread (see pthreads(7)).

bash
sudo apt install g++ cmake libgtest-dev
g++ -std=c++20 -Wall -Wextra heater_test.cpp -lgtest -lgtest_main -pthread -o heater_test
./heater_test

The runner's output has a fixed shape; this is what libgtest-dev 1.14.0 on Ubuntu 24.04 printed for those two tests, and the millisecond values on your machine will differ:

text
Running main() from ./googletest/src/gtest_main.cc
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from HeaterSm
[ RUN      ] HeaterSm.StartsIdle
[       OK ] HeaterSm.StartsIdle (0 ms)
[ RUN      ] HeaterSm.StartMovesToHeating
[       OK ] HeaterSm.StartMovesToHeating (0 ms)
[----------] 2 tests from HeaterSm (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test suite ran. (0 ms total)
[  PASSED  ] 2 tests.

A failed check prints the file and line, the two expressions, and their actual values, then the summary lists the failed tests by name. In the CMake project from the CMake setup lesson the same binary is three lines:

cmake
find_package(GTest REQUIRED)
add_executable(heater_test heater_test.cpp)
target_link_libraries(heater_test PRIVATE GTest::gtest_main)
02

Fixtures and assertions: TEST_F, EXPECT versus ASSERT

4 min read

The two tests above each construct a Heater, and most interesting tests need it already Heating. Repeating that arrangement in every body is noise, and noise drifts. A removes the repetition without sharing state.

cpp
class HeaterRunning : public ::testing::Test {
protected:
    void SetUp() override { h.handle(Event::Start); }
    Heater h;
};

TEST_F(HeaterRunning, StopReturnsToIdle) {
    h.handle(Event::Stop);                 // Act
    EXPECT_EQ(h.state(), State::Idle);
    EXPECT_EQ(h.heating_entries(), 1);
    EXPECT_EQ(h.heating_exits(), 1);
}

TEST_F(HeaterRunning, OvertempEntersFault) {
    h.handle(Event::Overtemp);
    EXPECT_EQ(h.state(), State::Fault);
    EXPECT_EQ(h.heating_exits(), 1);
}

The first argument of TEST_F must be the fixture class name, exactly, and that name is also the suite name. A suite cannot mix TEST and TEST_F: when we first compiled the lesson with the fixture also called HeaterSm, GoogleTest 1.14 failed both fixture tests with All tests in the same test suite must use the same test fixture class, so mixing TEST_F and TEST in the same test suite is illegal. That is why the fixture here is HeaterRunning while the plain tests above stay in HeaterSm. The body runs as a member of a class derived from your fixture, so protected members like h are directly visible. The lifecycle is fixed:

Step by stepWhat runs for each TEST_F, in order
  1. Fixture constructor: a brand-new fixture object is created for this test only.

  2. SetUp(): shared arrangement runs; here the heater is moved to Heating.

  3. Test body: your Act and Assert code.

  4. TearDown(): shared cleanup, if you define it.

  5. Fixture destructor: RAII members clean themselves up.

Because the object is fresh for every test, OvertempEntersFault sees heating_entries() == 1 even if the previous test drove the heater through ten cycles. No test can leak state into the next one. You can use the constructor and destructor instead of SetUp and TearDown, but prefer SetUp for setup that can fail: ASSERT_* works there, while a fatal assertion cannot be used inside a constructor.

Now the two assertion families. EXPECT_* is non-fatal: it records a failure and the body keeps running. ASSERT_* is fatal: it records a failure and returns from the current function immediately, skipping the rest of the body. The strategy follows from that: use ASSERT for preconditions whose failure makes the rest meaningless or dangerous, and EXPECT for the independent checks you want reported together. If a pointer must be non-null before you dereference it, write ASSERT_NE(ptr, nullptr); so a null never reaches the dereference. If you are checking three counters after one event, use three EXPECTs: one run then tells you all three truths, not just the first failure.

EXPECT_* versus ASSERT_*EXPECT_*ASSERT_*On failurerecords,continuesrecords,returnsRest of bodystill runsskippedBest forindependentcheckspreconditionsIn a void helpersafeexits helperonly
EXPECT_* continues after a failure; ASSERT_* returns from the current function

The comparison operators come in families: EXPECT_EQ, NE, LT, LE, GT, GE for comparable values, EXPECT_TRUE and EXPECT_FALSE for conditions, EXPECT_STREQ for C strings (comparing char* with EXPECT_EQ compares addresses, not text), and EXPECT_NEAR for floating-point values with an explicit tolerance. We ran a small demo to confirm it: a void helper containing ASSERT_EQ(1, 2) was called from a test body, the helper stopped at the failed assertion, and the body went on to run its next check (still ran appeared in the report). Every assertion accepts a streamed message: EXPECT_EQ(h.state(), State::Fault) << "after Overtemp"; adds context to the failure report. When State is an enum class, GoogleTest cannot print its names: the failure we provoked showed Which is: 4-byte object <01-00 00-00> for State::Heating. Define operator<< or PrintTo for the enum to get readable reports.

ASSERT_* inside a helper only exits the helper

A fatal assertion returns from the function it is written in. Inside a void helper called from a test body, ASSERT_* exits the helper, and the body keeps running on broken preconditions. At the call site write ASSERT_NO_FATAL_FAILURE(CheckPreconditions()); so a fatal failure inside the helper also stops the test.

03

Parameterized tests: one body, many cases

3 min read

A state machine's contract is a table: from this state, on this event, land in that state. Writing one TEST_F per row means copying the same body six times, and copies drift when the machine changes. A turns the table into data.

The fixture derives from ::testing::TestWithParam<Case>, a convenience base that combines testing::Test with the parameter interface. The body is written with TEST_P and reads the current value with GetParam().

cpp
struct Case { State from; Event event; State to; };

class HeaterTransitions : public ::testing::TestWithParam<Case> {};

TEST_P(HeaterTransitions, LandsInTargetState) {
    const Case c = GetParam();
    Heater h{c.from};                // Arrange
    h.handle(c.event);               // Act
    EXPECT_EQ(h.state(), c.to);      // Assert
}

INSTANTIATE_TEST_SUITE_P(Table, HeaterTransitions,
    ::testing::Values(
        Case{State::Idle,    Event::Start,    State::Heating},
        Case{State::Heating, Event::Stop,     State::Idle},
        Case{State::Heating, Event::Overtemp, State::Fault},
        Case{State::Fault,   Event::Reset,    State::Idle},
        Case{State::Idle,    Event::Stop,     State::Idle},
        Case{State::Fault,   Event::Start,    State::Fault}));

Note the last two rows: ignored events are part of the contract too, and the table tests them with the same body. INSTANTIATE_TEST_SUITE_P takes a prefix, the fixture name, and a generator. ::testing::Values lists values explicitly; ::testing::ValuesIn reads them from a container or array, ::testing::Range produces integers, ::testing::Bool produces false and true, and ::testing::Combine builds tuples from several generators. Each value, combined with each TEST_P body in the fixture, becomes one independent test with its own fixture instance and its own pass or fail. The generated names carry the prefix and an index: Table/HeaterTransitions.LandsInTargetState/0 through /5.

From table rows to testsCase table6 rows ofdataINSTANTIATE_TEST_SUITE_P::testing::ValuesTEST_P bodyruns onceper value6 tests12 with twobodiesCase table6 rows ofdataINSTANTIATE_TEST_SUITE_P::testing::ValuesTEST_P bodyruns onceper value6 tests12 with twobodies
One TEST_P body plus six table rows becomes six tests; add a second body and the same rows yield twelve

The runner flags work on these names like any others: ./heater_test --gtest_list_tests lists every generated test without running it, and ./heater_test --gtest_filter='Table/*' runs only this suite. When a row fails, the report names the exact index, and you can rerun that single case with --gtest_filter='*LandsInTargetState/2'. You can pass a name-generator lambda as a fourth argument to INSTANTIATE_TEST_SUITE_P to replace the index with a readable label, and define PrintTo for your Case type so failure output shows the row's contents.

One rule to remember: a TEST_P suite with no INSTANTIATE_TEST_SUITE_P is reported as a failure when the binary runs. GoogleTest treats an uninstantiated parameterized suite as an error, not as a test that is silently skipped, so you cannot forget the table without noticing. We tried it: the run ended with GoogleTestVerification.UninstantiatedParameterizedTestSuite<Un> marked FAILED, plus a hint to use GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST if the omission is deliberate. With the lesson's six rows, the full test binary ran 16 tests and all passed (2 plain, 2 fixture, 6 table rows, and 6 typed tests), and --gtest_filter="*LandsInTargetState/2" ran exactly one test.

For the lab you will add a second TEST_P to this same fixture: one that checks entry and exit counters after each event, including that ignored events leave both counters untouched. Two bodies over six rows: twelve tests from one table.

04

Typed tests: the same laws for every type

2 min read

Value-parameterized tests vary run-time data through one compiled body. A varies the type itself. That is what you want for the templates from earlier lessons: a retry counter, a bounded buffer, or a register wrapper must obey the same laws whether its parameter is unsigned char or std::uint64_t, and only a compile-time mechanism can exercise type-specific behaviour such as the width of std::numeric_limits<T>::max().

Take a saturating retry counter: it increments but never wraps.

cpp
#include <limits>

template <typename T>
class RetryCounter {
public:
    RetryCounter() = default;
    explicit RetryCounter(T start) : count_{start} {}
    void bump() {
        if (count_ < std::numeric_limits<T>::max()) ++count_;
    }
    T count() const { return count_; }
private:
    T count_ = 0;
};

The fixture for typed tests must itself be a class template. TYPED_TEST_SUITE binds it to a ::testing::Types list, and each body is written with TYPED_TEST, where TypeParam is an alias for the current type.

cpp
template <typename T>
class RetryCounterTest : public ::testing::Test {};

using CounterTypes =
    ::testing::Types<unsigned char, unsigned int, std::uint64_t>;
TYPED_TEST_SUITE(RetryCounterTest, CounterTypes);

TYPED_TEST(RetryCounterTest, BumpsFromZero) {
    RetryCounter<TypeParam> c;
    c.bump();
    EXPECT_EQ(c.count(), 1);
}

TYPED_TEST(RetryCounterTest, SaturatesAtMax) {
    constexpr TypeParam max = std::numeric_limits<TypeParam>::max();
    RetryCounter<TypeParam> c{max};
    c.bump();
    EXPECT_EQ(c.count(), max);
}

Three types times two bodies: six tests (the runner printed them as RetryCounterTest/0, where TypeParam = unsigned char and so on, with unsigned long for std::uint64_t on this platform), each compiled separately, and the failure report identifies which type failed. If the fixture declares members, access them as this->member inside TYPED_TEST: the base class depends on a template parameter, so unqualified lookup does not find its names without this->. The saturation test is the point of the whole mechanism: with TEST_P you could not even express "start at the maximum of the parameter's type", because the type is fixed when the single body is compiled. Use value parameters for tables of inputs, typed tests for contracts that must hold across instantiations, and know that TYPED_TEST_SUITE_P exists when you need both axes at once.

The heater's actions in this lesson were counters, which kept everything on the host. Real firmware drives a GPIO pin and talks to a sensor, and you still want to verify that the right calls happen in the right order without a board on the desk. The next lesson, GoogleMock and test doubles for hardware, answers that: mock objects that record and check every interaction.

Key takeaways

  • On Ubuntu 24.04, libgtest-dev ships headers and static libraries; link with -lgtest -lgtest_main -pthread and gtest_main supplies main.
  • EXPECT_* records a failure and continues the test; ASSERT_* records a failure and returns from the current function immediately.
  • Every TEST_F runs on a fresh fixture object, with SetUp before the body and TearDown after it.
  • Each INSTANTIATE_TEST_SUITE_P value combined with each TEST_P body becomes one independent test; typed tests instead instantiate one body per type at compile time.
Reflect
  1. Explain to a colleague, in two sentences: write TEST and TEST_F cases that follow the Arrange, Act, Assert pattern
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close