Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update docs to include how to use lambdas within regular test cases? #2513

Open
robamu opened this issue Sep 6, 2022 · 2 comments
Open

Update docs to include how to use lambdas within regular test cases? #2513

robamu opened this issue Sep 6, 2022 · 2 comments

Comments

@robamu
Copy link

robamu commented Sep 6, 2022

Hello,

The feature of nesting multiple sections into each other is really useful. Sometimes, I'd prefer something like functions though, where I can share the same code (which might include CHECKs and REQUIREs) across multiple sections. Maybe I missed something in the documentation, but I have found C++ lambdas to be extremely useful for this, and I can't use regular function definitions inside the TEST_CASE scope.

For example consider something like this

#include <catch2/catch_test_macros.hpp>

TEST_CASE("Test", "[test]") {
    uint32_t answer = 42;
    uint32_t foo = 10;

    auto sharedTestCode = [&](bool changeAnswer) {
        if(changeAnswer) {
            answer = foo;
        }
        CHECK(foo == 10);
    };

    SECTION("Section 0") {
        sharedTestCode(false);
        CHECK(answer == 42);
    }

    SECTION("Section 1") {
        sharedTestCode(true);
        CHECK(answer == 10);
    }

}

Do you think this is something worth mentioning in the doucmentation? Maybe this is also a case where a test fixture would be a better option in that case, but using lambdas has worked well enough for me to use the recommended way to use Catch2.

Kind Regards
Robin Müller

@robamu robamu changed the title Update docs to include how to use lambdas? Update docs to include how to use lambdas within regular test cases? Sep 6, 2022
@nandanvasudevan
Copy link

I do this all the time, isn't it just C++?

@robamu
Copy link
Author

robamu commented Oct 4, 2022

One could argue it's just C++, but it is usually possible to do work in C++ without lambdas entirely, especially when coming from a C background. In the context of Catch2 I have not found a way to have something similar to functions inside a Catch2 test case without lambdas. That's why I though it might be a nice idea to mention/include it in the docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants