Springuptech
← Back to Insights

Getting Started with C++ Unit Testing Using GoogleTest on Ubuntu — CMake FetchContent Setup, First Tests, GoogleMock, and Testing std::filesystem File Utilities

A step-by-step guide to setting up C++ unit tests with GoogleTest and GoogleMock on Ubuntu. It covers installing with CMake FetchContent (compared with the older build-from-source approach), first tests and fixtures, a mock example, running with ctest, and a complete example that tests C++17 std::filesystem functions for counting files, changing permissions recursively and setting modification times.

Jaeyong RohPublished 14 min read

When you maintain a C++ project, especially a long-running Linux server program or an embedded Linux application, there is a constant worry: "If I change this function, will something else break?" Without test code, the only option is to build it, deploy it to the device or server, and check the logs by eye.

GoogleTest (gtest) is the most widely used framework for adding unit tests to C++ code like this. GoogleMock (gmock), which creates mock objects, lives in the same repository. This article walks through everything in one go, from installing GoogleTest on Ubuntu to actually testing file utility functions written with C++17 std::filesystem. We built and ran the example code in this article as written and confirmed that all tests pass.

Prerequisites

You need the following packages on Ubuntu:

sudo apt update
sudo apt install build-essential cmake git
  • Compiler: starting with GoogleTest 1.17, released in 2025, C++17 or later is required. The examples here use std::filesystem, so we build with C++17 anyway.
  • GCC version: with GCC 8 you had to link -lstdc++fs separately to use std::filesystem. GCC 9 and later (the default compiler since Ubuntu 20.04) do not need it.
  • CMake: GoogleTest 1.17 requires CMake 3.16 or later. Check with cmake --version.

Three ways to install GoogleTest

Method How Pros Cons
CMake FetchContent (recommended) Downloads a pinned version at build time and builds it with your project Version pinned to the project, no sudo, reproducible on other machines and CI Needs internet access on the first build
apt packages sudo apt install libgtest-dev libgmock-dev Simple GoogleTest version depends on the Ubuntu release
Build from source and install system-wide (older way) Clone, build, sudo cmake --install Works offline once installed Only one version system-wide, risk of mismatched compile options

The official GoogleTest documentation also recommends building the library from source together with your project rather than installing a precompiled copy. In C++, mixing libraries built with different compile options (language standard, debug/release settings and so on) can cause subtle problems. That is why this article uses FetchContent by default and covers the older approach separately later.

Example project layout

We will create a small project like this:

fileutil/
├── CMakeLists.txt
├── include/
│   └── fileutil.h
├── src/
│   └── fileutil.cpp
└── tests/
    ├── fileutil_test.cpp
    └── cleanup_job_test.cpp

src holds the production code and tests holds the test code. Packaging the production code as a library (fileutil) lets both the application and the test program link the same code.

Writing CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(fileutil LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/refs/tags/v1.17.0.zip
)
FetchContent_MakeAvailable(googletest)

# Production code under test
add_library(fileutil src/fileutil.cpp)
target_include_directories(fileutil PUBLIC include)

enable_testing()

# Test executable
add_executable(fileutil_test
  tests/fileutil_test.cpp
  tests/cleanup_job_test.cpp
)
target_link_libraries(fileutil_test PRIVATE fileutil GTest::gtest_main GTest::gmock)

include(GoogleTest)
gtest_discover_tests(fileutil_test)

A few points worth noting:

  • Put an explicit tag (version) in the URL of FetchContent_Declare. Pointing at the main branch means your build can break one day without warning.
  • Linking GTest::gtest_main means you don't have to write main() yourself. The main() provided by GoogleTest finds and runs all tests.
  • GTest::gmock is needed when you use mock objects.
  • gtest_discover_tests() registers each test inside the test executable as an individual test in ctest.

Recent CMake versions may print a DOWNLOAD_EXTRACT_TIMESTAMP warning (CMP0135) for URL downloads. It is a developer warning and does not affect the build result.

The code under test: std::filesystem file utilities

We will test three file-related functions that server programs commonly need, plus a small job class that uses them:

  1. Count regular files under a folder (including subfolders)
  2. Change permissions of a folder and everything inside it recursively (similar to chmod -R, but with separate permissions for folders and files)
  3. Change a file's last write time

include/fileutil.h

#pragma once
#include <cstddef>
#include <filesystem>
#include <string>

namespace fileutil {

namespace fs = std::filesystem;

// Count regular files under dir (including subfolders).
std::size_t count_regular_files(const fs::path& dir);

// Change permissions of dir and everything below it.
// Folders and files get separate permissions.
void set_permissions_recursive(const fs::path& dir,
                               fs::perms dir_perms,
                               fs::perms file_perms);

// Change a file's last write time.
void set_mtime(const fs::path& file, fs::file_time_type when);

// Abstracts whatever sends notifications (replaced by a mock in tests)
class Notifier {
public:
    virtual ~Notifier() = default;
    virtual void Send(const std::string& message) = 0;
};

// Sends a notification when a folder holds more files than the limit
class CleanupJob {
public:
    CleanupJob(Notifier& notifier, std::size_t limit)
        : notifier_(notifier), limit_(limit) {}
    bool Check(const fs::path& dir);

private:
    Notifier& notifier_;
    std::size_t limit_;
};

}  // namespace fileutil

src/fileutil.cpp

#include "fileutil.h"

namespace fileutil {

std::size_t count_regular_files(const fs::path& dir) {
    std::size_t count = 0;
    std::error_code ec;
    fs::recursive_directory_iterator it(
        dir, fs::directory_options::skip_permission_denied, ec);
    if (ec) {
        throw fs::filesystem_error("count_regular_files", dir, ec);
    }
    for (const auto& entry : it) {
        // Do not count symbolic links themselves
        if (entry.is_regular_file(ec) && !entry.is_symlink(ec)) {
            ++count;
        }
    }
    return count;
}

void set_permissions_recursive(const fs::path& dir,
                               fs::perms dir_perms,
                               fs::perms file_perms) {
    fs::permissions(dir, dir_perms);  // throws filesystem_error on failure
    for (const auto& entry : fs::recursive_directory_iterator(dir)) {
        if (entry.is_symlink()) {
            continue;  // skip so we never change files outside the tree
        }
        if (entry.is_directory()) {
            fs::permissions(entry.path(), dir_perms);
        } else if (entry.is_regular_file()) {
            fs::permissions(entry.path(), file_perms);
        }
    }
}

void set_mtime(const fs::path& file, fs::file_time_type when) {
    fs::last_write_time(file, when);  // throws filesystem_error on failure
}

bool CleanupJob::Check(const fs::path& dir) {
    const std::size_t n = count_regular_files(dir);
    if (n > limit_) {
        notifier_.Send(dir.string() + " has " + std::to_string(n) + " files");
        return true;
    }
    return false;
}

}  // namespace fileutil

Some details in this code are deliberate:

  • skip_permission_denied: when the iterator meets a subfolder it cannot read, it skips it instead of throwing. Without this option, counting a folder with mixed permissions, such as /var/log, throws partway through.
  • Symbolic links: recursive_directory_iterator does not descend into links to folders by default, but fs::permissions() changes the permissions of the link's target by default. If you don't skip links, you may end up changing permissions on files outside the working folder.
  • Separate folder and file permissions: the common "0777 on everything" approach also makes regular files executable, which is bad for security. Folders need the execute (x) bit to be entered, but regular files don't, so setting them separately is safer.

Writing your first test

The most basic GoogleTest form is TEST(TestSuiteName, TestName).

#include <gtest/gtest.h>

int add(int a, int b) { return a + b; }

TEST(AddTest, AddsTwoNumbers) {
    EXPECT_EQ(add(2, 3), 5);
}

There are two kinds of assertion macros, EXPECT_* and ASSERT_*.

Macro On failure When to use
EXPECT_EQ, EXPECT_TRUE, etc. Records the failure and keeps running the test Most checks
ASSERT_EQ, ASSERT_TRUE, etc. Records the failure and returns from the current test function immediately Preconditions without which the rest is meaningless (e.g. failing to open a file)

The ones you will use most are EXPECT_EQ/EXPECT_NE (equal/not equal), EXPECT_LT/EXPECT_GE (comparisons), EXPECT_TRUE/EXPECT_FALSE, and EXPECT_THROW/EXPECT_NO_THROW (whether an exception is thrown). Sticking to an order such as EXPECT_EQ(actual, expected) makes failure messages easier to read.

Handling temporary folders with fixtures

The most important rule when testing file system functions is to create a fresh temporary folder for every test and delete it afterwards. Testing against real working folders gives different results each time and, in the worst case, can damage important files.

When several tests share the same setup and cleanup, create a fixture class and use TEST_F instead of TEST. SetUp() runs right before each test and TearDown() right after.

tests/fileutil_test.cpp

#include "fileutil.h"

#include <chrono>
#include <fstream>
#include <random>

#include <gtest/gtest.h>

namespace fs = std::filesystem;
using namespace std::chrono_literals;

namespace {

void touch(const fs::path& p) {
    std::ofstream(p) << "x";
}

// Creates an empty temporary folder per test and removes it afterwards
class TempDirTest : public ::testing::Test {
protected:
    void SetUp() override {
        std::random_device rd;
        root_ = fs::temp_directory_path() /
                ("fileutil_test_" + std::to_string(rd()));
        fs::create_directories(root_);
    }
    void TearDown() override {
        std::error_code ec;
        // Restore permissions first so the folder can always be removed
        fs::permissions(root_, fs::perms::owner_all,
                        fs::perm_options::add, ec);
        fs::remove_all(root_, ec);
    }
    fs::path root_;
};

}  // namespace

TEST_F(TempDirTest, EmptyDirectoryHasNoFiles) {
    EXPECT_EQ(fileutil::count_regular_files(root_), 0u);
}

TEST_F(TempDirTest, CountsFilesInSubdirectoriesButNotDirectories) {
    fs::create_directories(root_ / "a" / "b");
    touch(root_ / "1.txt");
    touch(root_ / "a" / "2.txt");
    touch(root_ / "a" / "b" / "3.txt");

    EXPECT_EQ(fileutil::count_regular_files(root_), 3u);
}

TEST_F(TempDirTest, MissingDirectoryThrows) {
    EXPECT_THROW(fileutil::count_regular_files(root_ / "nope"),
                 fs::filesystem_error);
}

TEST_F(TempDirTest, SetsDifferentPermissionsForDirsAndFiles) {
    fs::create_directories(root_ / "sub");
    touch(root_ / "sub" / "data.txt");

    const auto dir_perms = fs::perms::owner_all | fs::perms::group_read |
                           fs::perms::group_exec;                  // 0750
    const auto file_perms = fs::perms::owner_read | fs::perms::owner_write |
                            fs::perms::group_read;                 // 0640

    fileutil::set_permissions_recursive(root_, dir_perms, file_perms);

    EXPECT_EQ(fs::status(root_ / "sub").permissions(), dir_perms);
    EXPECT_EQ(fs::status(root_ / "sub" / "data.txt").permissions(),
              file_perms);
}

TEST_F(TempDirTest, SetsLastWriteTime) {
    const auto file = root_ / "old.log";
    touch(file);
    const auto target = fs::file_time_type::clock::now() - 72h;

    fileutil::set_mtime(file, target);

    // Allow up to 1 second for differences in file system time precision
    const auto diff = fs::last_write_time(file) - target;
    EXPECT_LT(std::chrono::abs(diff), 1s);
}

Good test names tell you how the function should behave just by reading them. The tests cover normal, boundary and error cases: "an empty folder has zero files", "files in subfolders are counted but folders are not", "a missing folder throws".

The modification-time test allows a difference of up to one second instead of an exact EXPECT_EQ, because file systems store timestamps with different precision. Time-related tests need a tolerance like this; otherwise they become flaky and fail depending on the environment.

Swapping out dependencies with GoogleMock

CleanupJob sends a notification through Notifier when the file count exceeds the limit. In production that notification might go to email, a messenger or a monitoring system, and you don't want real notifications going out every time the tests run. Instead, swap in a mock object and check only "how many times, and with what arguments, the notification function was called."

tests/cleanup_job_test.cpp

#include "fileutil.h"

#include <fstream>
#include <random>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

namespace fs = std::filesystem;
using ::testing::_;
using ::testing::HasSubstr;

class MockNotifier : public fileutil::Notifier {
public:
    MOCK_METHOD(void, Send, (const std::string& message), (override));
};

class CleanupJobTest : public ::testing::Test {
protected:
    void SetUp() override {
        std::random_device rd;
        dir_ = fs::temp_directory_path() /
               ("cleanup_job_test_" + std::to_string(rd()));
        fs::create_directories(dir_);
        for (int i = 0; i < 3; ++i) {
            std::ofstream(dir_ / ("f" + std::to_string(i))) << i;
        }
    }
    void TearDown() override { fs::remove_all(dir_); }

    fs::path dir_;
    MockNotifier notifier_;
};

TEST_F(CleanupJobTest, NotifiesWhenOverLimit) {
    EXPECT_CALL(notifier_, Send(HasSubstr("has 3 files"))).Times(1);

    fileutil::CleanupJob job(notifier_, 2);
    EXPECT_TRUE(job.Check(dir_));
}

TEST_F(CleanupJobTest, StaysQuietAtOrBelowLimit) {
    EXPECT_CALL(notifier_, Send(_)).Times(0);

    fileutil::CleanupJob job(notifier_, 3);
    EXPECT_FALSE(job.Check(dir_));
}
  • Declare a mock function with MOCK_METHOD(return type, name, (arguments), (override));. Numbered macros such as MOCK_METHOD1, which you will see in older material, are the old style; today you use the single MOCK_METHOD.
  • Write EXPECT_CALL before running the code under test. You declare "this call will happen" first, and the expectation is verified when the test ends (when the mock object is destroyed).
  • Matchers such as HasSubstr and _ (any value) let you describe argument conditions flexibly.

To use mocks, production code must depend on an interface (virtual functions) rather than a concrete class. This is the first wall you hit when adding tests to legacy code. Simply moving code that calls external systems behind a small interface greatly widens what you can test.

Building and running

Run these commands from the project's top-level folder:

cmake -S . -B build
cmake --build build -j
cd build && ctest --output-on-failure

When all tests pass, you see:

100% tests passed out of 7

You can also run the test executable directly. This shows GoogleTest's own detailed output and lets you use its options:

./build/fileutil_test                                  # run everything
./build/fileutil_test --gtest_filter='CleanupJob*'     # select by name
./build/fileutil_test --gtest_repeat=100 --gtest_shuffle  # repeat and shuffle

--gtest_repeat and --gtest_shuffle are useful for finding tests that fail only occasionally depending on order or timing. Tests that share files or global variables tend to show up this way.

When a test fails, GoogleTest shows the file and line, and both the actual and expected values. For example, if the file count were wrong, you would see something like this:

fileutil_test.cpp:52: Failure
Expected equality of these values:
  fileutil::count_regular_files(root_)
    Which is: 4
  3u
    Which is: 3

Pitfalls when setting the modification time from a date string

In practice you may need to set a file's modification time from a string such as 2024-03-01T09:30:00Z. There are two traps here.

1. mktime() interprets the time as local time. A string ending in Z is UTC, but if you pass the std::tm read with std::get_time to mktime(), it is computed in local time. On a server set to Korea Standard Time (UTC+9), the result is off by nine hours. On Linux (glibc) you can use timegm(), which computes in UTC. It is not a standard C++ function, so check availability if you port to another platform.

2. C++17 has no standard way to convert a system_clock time to file_time_type. The clock used by file_time_type can differ between implementations, and conversion tools such as std::chrono::clock_cast only arrived in C++20. In C++17, a common approach is an approximate conversion using the offset from the current time. For file modification times, an error of a few microseconds does not matter.

#include <chrono>
#include <ctime>
#include <filesystem>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include <string>

namespace fs = std::filesystem;

// Convert a UTC string such as "2024-03-01T09:30:00Z" to a system_clock time
std::chrono::system_clock::time_point parse_utc(const std::string& text) {
    std::tm tm{};
    std::istringstream in(text);
    in >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
    if (in.fail()) {
        throw std::invalid_argument("bad timestamp: " + text);
    }
    // mktime() treats tm as local time. This is UTC, so use timegm().
    const std::time_t t = timegm(&tm);
    return std::chrono::system_clock::from_time_t(t);
}

// C++17: approximate conversion from system_clock time to file_time_type
fs::file_time_type to_file_time(std::chrono::system_clock::time_point tp) {
    const auto offset = tp - std::chrono::system_clock::now();
    return fs::file_time_type::clock::now() +
           std::chrono::duration_cast<fs::file_time_type::duration>(offset);
}

// Usage
// fileutil::set_mtime(path, to_file_time(parse_utc("2024-03-01T09:30:00Z")));

It is worth adding tests for these conversion functions too. For example, checking that parse_utc("1970-01-01T00:00:00Z") returns time_t 0 even when the TZ environment variable is set to Asia/Seoul catches time zone mistakes right away.

The older way: building from source and installing system-wide

If FetchContent is not an option, for example on a development server without internet access, you can build GoogleTest once, install it on the system and use it from there.

git clone --branch v1.17.0 --depth 1 https://github.com/google/googletest.git
cd googletest
cmake -S . -B build -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local
cmake --build build -j
sudo cmake --install build

We recommend /usr/local instead of /usr as the install location. /usr is managed by apt, so installing the libgtest-dev package later could overwrite files or be overwritten. After installing, replace the FetchContent block in your project's CMakeLists.txt with:

find_package(GTest REQUIRED)
# target_link_libraries stays the same: GTest::gtest_main, GTest::gmock

Because the whole system shares one version with this approach, it becomes hard to manage when several projects need different GoogleTest versions or C++ standards. When possible, pinning the version per project with FetchContent is better. For offline environments, another option is to keep the GoogleTest source inside your project repository and build it with add_subdirectory().

Common problems and how to check them

Symptom Cause Fix
undefined reference to main gtest_main not linked and no main() written Link GTest::gtest_main or write your own main()
undefined reference to testing::... gtest/gmock libraries not linked Add GTest::... to target_link_libraries
C++ standard errors from GoogleTest headers Building GoogleTest 1.17 with C++14 or earlier Set CMAKE_CXX_STANDARD to 17 or later
std::filesystem link errors on GCC 8 Older GCC needs a separate library Link stdc++fs or use GCC 9 or later
Permission tests fail only on CI Running as root (e.g. in Docker) bypasses permission checks Run as a regular user, or skip with GTEST_SKIP() when root
Occasional failures with ctest -j Tests share the same temporary folder or file names Use a unique temporary folder per test
Mock expectation not satisfied Ordering problem, or the call really didn't happen Make sure EXPECT_CALL is written before the code under test runs

The root issue is easy to miss. Root can read and write files regardless of permissions, so a test like "skip folders that cannot be read" does not behave as intended when run as root. Adding a guard such as if (geteuid() == 0) GTEST_SKIP() << "permission checks are bypassed for root"; at the start of such tests keeps you from misreading the results.

Summary

  • Build GoogleTest together with your project using CMake FetchContent, with the version pinned. (1.17 and later need C++17.)
  • Split production code into a library; link the test executable against GTest::gtest_main and GTest::gmock.
  • Register tests with gtest_discover_tests() and run them with ctest --output-on-failure.
  • For file system tests, create a unique temporary folder per test and delete it in TearDown().
  • Cover normal, boundary and error cases, and use a tolerance when comparing times.
  • Move external system calls behind an interface and swap them with MOCK_METHOD. Write EXPECT_CALL before running the code.
  • When changing permissions recursively, skip symbolic links and give folders and files separate permissions.
  • For UTC strings, use timegm() (Linux) or C++20 time zone features instead of mktime().

It is hard to give an untested C++ project complete test coverage from day one. But if you start with the function you are changing now and a few utilities that often cause trouble, the anxiety of making changes drops noticeably. If you need help maintaining Linux or embedded Linux C++ programs, setting up a test environment, or cleaning up an aging build setup, contact Springuptech. We will look at your current code and build structure with you and suggest a realistic path forward.

※ This article expands on our lead engineer's earlier personal blog posts (in Korean): "Install Google Test and Google Mock on Ubuntu", "c++ 폴더 내의 파일 갯수 체크", "How to perform chmod recursively?", "linux 파일에 lastmodified date 쓰기".

C++GoogleTestCMakeUnit TestingLinux
J

Jaeyong Roh

Lead engineer at Springuptech · 22 years in software engineering

Have a project related to this topic?

Even if it is just an idea, we will help you work out what is possible.

Practical tips from real projects

11 min read

When Ports 80/443 Won't Open on an Oracle Cloud Free Server — The Two Firewall Layers: Security Lists and Ubuntu iptables

Why a web server on an Oracle Cloud (OCI) free instance is unreachable from outside, and how to fix it. Covers the two firewall layers — VCN security list / network security group ingress rules and the iptables rules shipped with the Ubuntu image — why the allow rule must come before the REJECT rule, saving with netfilter-persistent, a symptom-based diagnosis order, and putting Tomcat behind Nginx.

Oracle CloudLinuxiptables
Read more
8 min read

Building "MiniPlay", a Mini Games Site — Seven Languages, Leaderboards and Game Uploads with Build-Free Vanilla JavaScript

How we built a site with 20 instant-play browser mini games in five days — why we chose a no-build structure, how each game plugs in as an independent folder, generating pages in seven languages, Firebase sign-in and leaderboard security rules, and an admin page for uploading games.

PortfolioJavaScriptFirebase
Read more
13 min read

Building an Oracle Query That Alerts When the Failure Rate Exceeds 10% in the Last 5 Minutes — Date Arithmetic, SUM(CASE), HAVING, Indexes and Batch Integration

A step-by-step guide to an Oracle query that computes the failure rate of the last N minutes from a transaction log and flags when it crosses a threshold — covering DATE and TIMESTAMP arithmetic, time-window filtering, aggregation with SUM(CASE) and HAVING, division by zero and small samples, indexes, and calling it from a Pro*C batch.

OracleSQLMonitoring
Read more