302-Gen-Table.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // 302-Gen-Table.cpp
  2. // Shows how to use table to run a test many times with different inputs. Lifted from examples on
  3. // issue #850.
  4. #include <catch2/catch.hpp>
  5. #include <string>
  6. struct TestSubject {
  7. // this is the method we are going to test. It returns the length of the
  8. // input string.
  9. size_t GetLength( const std::string& input ) const { return input.size(); }
  10. };
  11. TEST_CASE("Table allows pre-computed test inputs and outputs", "[example][generator]") {
  12. using std::make_tuple;
  13. // do setup here as normal
  14. TestSubject subj;
  15. SECTION("This section is run for each row in the table") {
  16. std::string test_input;
  17. size_t expected_output;
  18. std::tie( test_input, expected_output ) =
  19. GENERATE( table<std::string, size_t>(
  20. { /* In this case one of the parameters to our test case is the
  21. * expected output, but this is not required. There could be
  22. * multiple expected values in the table, which can have any
  23. * (fixed) number of columns.
  24. */
  25. make_tuple( "one", 3 ),
  26. make_tuple( "two", 3 ),
  27. make_tuple( "three", 5 ),
  28. make_tuple( "four", 4 ) } ) );
  29. // run the test
  30. auto result = subj.GetLength(test_input);
  31. // capture the input data to go with the outputs.
  32. CAPTURE(test_input);
  33. // check it matches the pre-calculated data
  34. REQUIRE(result == expected_output);
  35. } // end section
  36. }
  37. /* Possible simplifications where less legacy toolchain support is needed:
  38. *
  39. * - With libstdc++6 or newer, the make_tuple() calls can be omitted
  40. * (technically C++17 but does not require -std in GCC/Clang). See
  41. * https://stackoverflow.com/questions/12436586/tuple-vector-and-initializer-list
  42. *
  43. * - In C++17 mode std::tie() and the preceeding variable delcarations can be
  44. * replaced by structured bindings: auto [test_input, expected] = GENERATE(
  45. * table<std::string, size_t>({ ...
  46. */
  47. // Compiling and running this file will result in 4 successful assertions