OpenSource-Hub

Catch2

프레임워크

catchorg/Catch2

유닛 테스트, TDD, BDD 및 마이크로 벤치마크 테스트를 지원하는 모던 C++ 테스트 프레임워크입니다.

개요

Catch2는 간결하고 자연스러운 테스트 작성 방식으로 유명한 C++ 테스트 프레임워크로, 섹션 기반 공유 설정/정리, BDD 매크로 및 기본적인 마이크로 벤치마크 기능을 지원합니다. 외부 종속성이 필요 없으며, 단일 헤더 파일 또는 컴파일된 라이브러리 형태로 사용할 수 있습니다.

README 미리보기

\n\n\n[](https://github.com/catchorg/catch2/releases)\n[](https://github.com/catchorg/Catch2/actions/workflows/linux-simple-builds.yml)\n[](https://github.com/catchorg/Catch2/actions/workflows/linux-other-builds.yml)\n[](https://github.com/catchorg/Catch2/actions/workflows/mac-builds.yml)\n[](https://ci.appveyor.com/project/catchorg/catch2)\n[](https://codecov.io/gh/catchorg/Catch2)\n[](https://godbolt.org/z/EdoY15q9G)\n[](https://discord.gg/4CWS9zD)\n\n\n## What is Catch2?\n\nCatch2 is mainly a unit testing framework for C++, but it also\nprovides basic micro-benchmarking features, and simple BDD macros.\n\nCatch2's main advantage is that using it is both simple and natural.\nTest names do not have to be valid identifiers, assertions look like\nnormal C++ boolean expressions, and sections provide a nice and local way\nto share set-up and tear-down code in tests.\n\n**Example unit test**\n```cpp\n#include \n\n#include \n\nuint32_t factorial( uint32_t number ) {\n    return number \n#include \n\n#include \n\nuint64_t fibonacci(uint64_t number) {\n    return number < 2 ? number : fibonacci(number - 1) + fibonacci(number - 2);\n}\n\nTEST_CASE("Benchmark Fibonacci", "[!benchmark]") {\n    REQUIRE(fibonacci(5) == 5);\n\n    REQUIRE(fibonacci(20) == 6'765);\n    BENCHMARK("fibonacci 20") {\n        return fibonacci(20);\n    };\n\n    REQUIRE(fibonacci(25) == 75'025);\n    BENCHMARK("fibonacci 25") {\n        return fibonacci(25);\n    };\n}\n```\n\n_Note that benchmarks are not run by default, so you need to run it explicitly\nwith the `[!benchmark]` tag._\n\n\n## Catch2 v3 has been released!\n\nYou are on the `devel` branch, where the v3 version is being developed.\nv3 brings a bunch of significant changes, the big one being that Catch2\nis no longer a single-header library. Catch2 now behaves as a normal\nlibrary, with multiple headers and separately compiled implementation.\n\nThe documentation is slowly being updated to take these changes into\naccount, but this work

FAQ (5)

문제 해결
잘못된 _MSVC_VER 매크로로 인해 MSVC에서 Catch2 v3.16.0이 최적화를 다시 활성화하지 못하는 문제를 해결하는 방법은?

Catch2 amalgamated 헤더(예: catch_amalgamated.hpp)에서 1523번 줄로 이동하여, 최적화를 다시 활성화하는 pragma를 감싸고 있는 전처리기 검사 부분에서 잘못된 매크로 _MSVC_VER를 _MSC_VER로 교체하십시오. 그런 다음 프로젝트를 다시 빌드하십시오. 수정 예시: #if defined(_MSVC_VER)를 #if defined(_MSC_VER)로 변경하십시오. 이 문제는 커밋 45f9ea1e798c2e128dcba53602ccbddfe5676f6f에서 도입되었으므로, 패치된 릴리스가 제공되면 이를 사용하고 그 전까지는 로컬 헤더 수정을 임시 해결 방법으로 유지하십시오.

원본 Issue #3211
문제 해결
실패한 테스트가 CTest를 통해 실행될 때만 추가 Catch2 진단 출력을 출력하려면 어떻게 해야 하나요?

-s와 함께 INFO()/WARN()을 사용하는 대신 Catch2 이벤트 리스너를 사용하세요. 진단 정보를 전역 변수 또는 스레드 안전 싱글턴에 저장한 다음, 테스트에 실패가 있을 때만 testCaseEnded()에서 stderr로 출력하세요. CTest의 --output-on-failure가 해당 stderr 출력을 표시해 줍니다.

#include <catch2/catch_test_macros.hpp>
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>

#include <iostream>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>

std::mutex g_failureInfoMutex;
std::vector<std::string> g_failureInfo;

#define FAIL_INFO(expr)                                      \
    do {                                                     \
        std::ostringstream oss;                              \
        oss << expr;                                         \
        std::lock_guard<std::mutex> lock(g_failureInfoMutex); \
        g_failureInfo.push_back(oss.str());                  \
    } while (false)

class FailureInfoListener : public Catch::EventListenerBase {
public:
    using EventListenerBase::EventListenerBase;

    void testCaseStarting(Catch::TestCaseInfo const&) override {
        std::lock_guard<std::mutex> lock(g_failureInfoMutex);
        g_failureInfo.clear();
    }

    void testCaseEnded(Catch::TestCaseStats const& stats) override {
        if (stats.totals.assertions.allOk()) {
            return;
        }

        std::cerr << "Additional failure information:\n";

        std::lock_guard<std::mutex> lock(g_failureInfoMutex);
        for (auto const& line : g_failureInfo) {
            std::cerr << line << '\n';
        }
    }
};

CATCH_REGISTER_LISTENER(FailureInfoListener)

테스트에서 다음과 같이 사용하세요:

TEST_CASE("GPU test") {
    FAIL_INFO("GPU: " << gpuName);
    REQUIRE(false);
}

다음 명령으로 실행하세요:

ctest --output-on-failure

Catch2는 레지스트리에서 리스너 인스턴스를 가져오는 방법을 제공하지 않으므로, 리스너는 공유 전역 변수를 읽어야 합니다. 여러 스레드에서 진단 정보를 기록할 수 있는 경우에는 뮤텍스를 사용하세요. 커스텀 리포터도 하나의 방법이지만, 이벤트 리스너가 더 간단한 권장 방식입니다.

원본 Issue #3183
문제 해결
Catch2 catch_discover_tests TEST_PREFIX에서 후행 공백을 어떻게 유지할 수 있나요?

Catch2 v2.13.4와 CMake v3.10.3에서는 TEST_PREFIX가 add_custom_command()를 통해 전달될 때 후행 공백이 손실됩니다. 빌드에서 사용하는 Catch.cmake(일반적으로 contrib/Catch.cmake, 160행 부근)를 편집하여 다음을:

-D "TEST_PREFIX=${_TEST_PREFIX}"

다음으로 바꾸세요:

-D "TEST_PREFIX='${_TEST_PREFIX}'"

이와 동등한 형식은 다음과 같습니다:

-D TEST_PREFIX='${_TEST_PREFIX}'

add_custom_command() 호출에서는 VERBATIM을 그대로 유지하세요. 테스트 검색 스크립트가 다시 생성되도록 재구성하고 다시 빌드하세요:

cmake -S . -B build
cmake --build build
ctest --test-dir build -N

이 변경을 적용하면 TEST_PREFIX "${TARGET} "는 <target><test name> 대신 <target> <test name>과 같은 CTest 이름을 생성합니다. Catch.cmake를 패치할 수 없는 경우에는 임시 해결 방법으로 ${TARGET}. 또는 ${TARGET}:과 같은 공백이 아닌 구분자를 사용하세요.

원본 Issue #2149
문제 해결
Clang 20에서 Catch2 빌드 실패 해결 방법: '-Wunreachable-code-return' 및 'no matching function for call to get_wrapper'?

Clang 20 빌드 수정 사항이 포함된 v3.9.1 이상으로 Catch2를 업그레이드하세요. Git 체크아웃의 경우 다음을 실행하세요:

git fetch --tags
git checkout v3.9.1
CXX=clang++ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build

Catch2 라이브러리만 필요하고 자체 테스트가 필요하지 않은 경우, 해결 방법으로 개발 빌드를 비활성화하세요:

CXX=clang++ cmake -S . -B build -DCATCH_DEVELOPMENT_BUILD=OFF
cmake --build build

오류는 개발/자체 테스트 타겟에서 발생하므로, CATCH_DEVELOPMENT_BUILD=OFF로 빌드하면 실패하는 테스트 파일들의 컴파일을 피할 수 있습니다. -Wno-error=unreachable-code-return을 사용하면 첫 번째 경고만 억제될 뿐 get_wrapper 템플릿 오류는 해결되지 않습니다.

원본 Issue #2991
문제 해결
macOS 또는 Alpine에서 TEMPLATE_PRODUCT_TEST_CASE 사용 시 발생하는 Catch2 "no matching function for call to 'get_wrapper'" 오류 해결 방법은?

이 문제는 테스트 문법이 아니라 libc++와 함께 사용된 Clang 20/21로 인해 발생합니다. Clang은 인자 개수(arity)가 서로 다른 타입 리스트와 함께 사용된 TEMPLATE_PRODUCT_TEST_CASE를 거부합니다. Clang 22에서 이 컴파일러 문제가 수정되었으며, Catch2 PR #3173에서 해결 방법이 추가되었습니다.

Catch2를 3.15.0에서 PR #3173이 포함된 더 최신 v3.x 릴리스 또는 최신 v3.x 버전으로 업그레이드하여 수정하세요. Meson 서브프로젝트의 경우 subprojects/catch2.wrap을 업데이트하고 다음을 실행하세요:

meson subprojects update catch2
meson setup --reconfigure build

CMake FetchContent의 경우 GIT_TAG를 최신 Catch2 v3.x 릴리스로 업데이트하고 재구성하세요.

대체 해결 방법:
- 컴파일러를 Clang 22로 업그레이드하세요.
- Catch2를 즉시 업그레이드할 수 없는 경우, catchorg/Catch2 PR #3173의 변경 사항을 체리픽하거나 백포트하세요.

원본 Issue #3115