catchorg / catchorg/Catch2

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

Open
#2,513 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
21.5k
Forks
3.5k
Avg merge
3d 16h
Merged PRs (30d)
2

Description

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

```cpp
#include

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.