Search code examples
c++unit-testingcatch2

How to add parameters to section names in Catch2


I'm using Catch2 to create a set of tests for some C++ legacy code and I have a function that I would like to test for a good amount of values. I have found that I can use the GENERATE keyword to create a data generator variable that will repeat the following scenario for each of the generated values, but my only issue is that when I launch the tests, I cannot distinguish which execution is for each value.

So for a minimal example like:

TEST_CASE("Evaluate output of is_odd() function") {
    auto i = GENERATE(1, 3, 5);
    SECTION("Check if i is odd"){ // <-- I want to fit the actual value of i in here.
        REQUIRE(is_odd(i));
    }
}

So if I launch the tests and I specify -s to see passed tests as well, I would like to see something like:

-------------------------------------------
Evaluate output of is_odd() function
  Check if 1 is odd
-------------------------------------------
...
-------------------------------------------
Evaluate output of is_odd() function
  Check if 3 is odd
-------------------------------------------
...
-------------------------------------------
Evaluate output of is_odd() function
  Check if 5 is odd
-------------------------------------------

I have tried creating a string containg i and concatenating it to the SECTION's name, but it didn't work, is there some way to achieve this?


Solution

  • This is possible, but not very obvious from the documentation. What you're looking for is a dynamic section:

    TEST_CASE("Evaluate output of is_odd() function") {
        auto i = GENERATE(1, 3, 5);
        DYNAMIC_SECTION("Check if " << i << " is odd"){ 
            REQUIRE(is_odd(i));
        }
    }