302-Gen-Table.cpp 2.1 KB

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