loctest

Language: CPP

Testing

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.

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.

Installation

cmake: add_subdirectory(loctest)
vcpkg: vcpkg install loctest
manual: Download loctest.hpp and include it in your project

Usage

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

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`.

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.

Error Handling

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.