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