Skip to content

What it is

loctest is a lightweight and minimal C++ testing framework designed to provide simple and readable unit tests. It focuses on clarity and small binary size, making it a good choice for embedded systems and projects that don’t require heavy testing infrastructure.

loctest provides macros for defining test cases and assertions. It is header-only and integrates easily into any project.

Installation

add_subdirectory(loctest)

Getting started

The smallest useful thing you can do with it, and what each part means.

Hello world test
#define LOCTEST_MAIN
#include <loctest/loctest.hpp>

TEST_CASE("Basic test") {
    int a = 2 + 2;
    REQUIRE(a == 4);
}
Defines a basic test case using `TEST_CASE` and `REQUIRE`.

Advanced usage

Where the library earns its place over a simpler alternative.

Multiple test cases
TEST_CASE("Addition works") {
    REQUIRE(2 + 3 == 5);
}

TEST_CASE("Multiplication works") {
    REQUIRE(3 * 3 == 9);
}
Multiple test cases can be defined independently.
Sections within a test
TEST_CASE("Math operations") {
    SECTION("Addition") {
        REQUIRE(1 + 1 == 2);
    }
    SECTION("Subtraction") {
        REQUIRE(5 - 2 == 3);
    }
}
Uses sections to organize related assertions inside one test case.
Custom messages
int x = 10;
int y = 5;
REQUIRE_MESSAGE(x > y, "Expected x > y, but got x=" << x << ", y=" << y);
Provides descriptive failure messages when an assertion fails.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

Undefined reference to main
Define `#define LOCTEST_MAIN` in exactly one source file.
Test case not running
Ensure the test file is compiled and linked into the test binary.
False positives on floating-point comparisons
Use approximate comparisons or tolerance checks for floating-point values.

Best practices

  • Use `TEST_CASE` names that clearly describe the expected behavior.
  • Group related assertions with `SECTION` for readability.
  • Add failure messages for complex expressions to aid debugging.
  • Keep tests small and focused to isolate failures.
  • Integrate loctest into CI pipelines for automated validation.

Background

Why it exists, and what it was reacting to.

loctest was created as part of the wave of minimal C++ testing libraries that emerged alongside Catch2 and doctest. Its main goal is to reduce boilerplate while keeping tests close to the production code. Developers adopt loctest for projects where simplicity, readability, and low overhead matter most.