如何在Catch2中生成多组Section的笛卡尔积?
在Catch2中实现SECTION的笛卡尔积执行
你的问题核心在于:Catch2的平级SECTION是独立执行分支的,不会自动跨组生成笛卡尔积。要实现你期望的多组SECTION组合执行,有两种常用方案:
方案一:嵌套SECTION结构
利用Catch2的SECTION嵌套特性,将第二组SECTION放入第一组的每个SECTION内部,这样外层每个分支都会触发内层所有分支的执行,自然生成笛卡尔积:
#include <catch2/catch_test_macros.hpp> #include <iostream> TEST_CASE("Section showcase") { SECTION("A1") { std::cout << "A1 "; SECTION("B1") { std::cout << "some intermedite code B1\n"; } SECTION("B2") { std::cout << "some intermedite code B2\n"; } } SECTION("A2") { std::cout << "A2 "; SECTION("B1") { std::cout << "some intermedite code B1\n"; } SECTION("B2") { std::cout << "some intermedite code B2\n"; } } }
这种方式直观,但如果选项数量较多,会导致代码重复。
方案二:使用GENERATE宏生成组合
对于选项较多的场景,推荐用Catch2的GENERATE宏(Catch2 v3支持更便捷的组合生成),直接定义所有可能的组合或通过范围自动生成笛卡尔积:
方式1:手动定义所有组合
#include <catch2/catch_test_macros.hpp> #include <iostream> #include <utility> TEST_CASE("Section showcase with generate") { auto [a_part, b_part] = GENERATE( std::make_pair("A1 ", "B1"), std::make_pair("A1 ", "B2"), std::make_pair("A2 ", "B1"), std::make_pair("A2 ", "B2") ); std::cout << a_part << "some intermedite code " << b_part << '\n'; }
方式2:通过范围自动生成组合(Catch2 v3+)
#include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> #include <iostream> #include <vector> TEST_CASE("Section showcase with combination generators") { std::vector<std::string> a_options = {"A1 ", "A2 "}; std::vector<std::string> b_options = {"B1", "B2"}; auto a_part = GENERATE(from_range(a_options)); auto b_part = GENERATE(from_range(b_options)); std::cout << a_part << "some intermedite code " << b_part << '\n'; }
GENERATE会自动遍历所有可能的参数组合,输出你期望的笛卡尔积结果,同时避免代码重复。
内容的提问来源于stack exchange,提问作者Stein
相关产品推荐
相关产品推荐

