Using Approval Tests With [Boost].UT

Introduction

The [Boost].UT test framework works well with Approval Tests.

[Boost].UT is a single header/single module, macro-free μ(micro)/Unit Testing Framework that requires C++17 / C++20

Notes pre-v.10.8.0:

Earlier versions of Approval Tests had issues with Ninja. Read more at Troubleshooting Misconfigured Build.

Requirements

Approval Tests for [Boost].UT requires that a file called the following is found:

#include <boost/ut.hpp>

(See snippet source)

It also requires:

Usage examples

Add the following two lines to your source code:

#define APPROVALS_UT
#include "ApprovalTests.hpp"

(See snippet source)

Below is an example of a call to an approval test inside a [Boost].UT test:

"ItCanVerifyAFile"_test = []() {
    ApprovalTests::Approvals::verify(
        "Approval Tests can verify text via the golden master method");
};

(See snippet source)

In the following example, two instances of ApprovalTests are called inside the same test. We need to use sections with different names, to prevent Approval Tests from using the same output file for both tests:

"ItCanUseMultipleVerify"_test = []() {
    {
        // Here we simulate test sections, so that Approval Tests uses different
        // output file names for the different verify() calls.
        auto section =
            ApprovalTests::NamerFactory::appendToOutputFilename("section 1");
        ApprovalTests::Approvals::verify(
            "Approval Tests can verify text via the golden master method");
    }
    {
        auto section =
            ApprovalTests::NamerFactory::appendToOutputFilename("section 2");
        ApprovalTests::Approvals::verify(
            "Approval Tests can verify different text via "
            "the golden master method");
    }
};

(See snippet source)

Code to copy for your first [Boost].UT Approvals test

Here is sample code to create your main() function and your first test, to set up Approval Tests’ [Boost].UT integration. We called this file ut_starter_test.cpp:

#define APPROVALS_UT
#include "ApprovalTests.hpp"

int main()
{
    using namespace boost::ut;
    using namespace ApprovalTests;

    // This puts "received" and "approved" files in approval_tests/ sub-directory,
    // keeping the test source directory tidy:
    auto directory = Approvals::useApprovalsSubdirectory("approval_tests");

    "Starter"_test = []() {
        // TODO Replace 42 with the value or object whose contents you are verifying.
        // For help, see:
        // https://approvaltestscpp.readthedocs.io/en/latest/generated_docs/ToString.html
        Approvals::verify(42);
    };
}

(See snippet source)

And finally, here is sample code to put in your CMakeLists.txt file:

set(EXE_NAME ut_starter)

set(CMAKE_CXX_STANDARD 20)
add_executable(${EXE_NAME}
        ut_starter_test.cpp
        )
target_link_libraries(${EXE_NAME} ApprovalTests::ApprovalTests boost.ut)

add_test(NAME ${EXE_NAME} COMMAND ${EXE_NAME})

(See snippet source)