使用参数化测试并在测试用例中传入不同的输入,每个输入都使用相应的catch2检查方法进行验证。以下是一个示例,假设要测试一个函数multiply,它在接收两个整数作为参数时返回它们的乘积。
#include
int multiply(int a, int b) {
return a * b;
}
TEST_CASE("multiply function tests", "[multiply]") {
SECTION("positive numbers") {
int a = 5;
int b = 10;
int expected = 50;
int result = multiply(a, b);
REQUIRE(result == expected);
}
SECTION("negative numbers") {
int a = -5;
int b = -10;
int expected = 50;
int result = multiply(a, b);
REQUIRE(result == expected);
}
SECTION("one zero and one positive number") {
int a = 0;
int b = 10;
int expected = 0;
int result = multiply(a, b);
REQUIRE(result == expected);
}
SECTION("one zero and one negative number") {
int a = -5;
int b = 0;
int expected = 0;
int result = multiply(a, b);
REQUIRE(result == expected);
}
}
该示例测试用例使用了参数化测试,它们都测试了不同类型的输入,使用了不同的catch2检查方法进行验证。当一个测试用例失败时,catch2将会输出错误信息(如失败测试的名称、失败断言的表达式等),并且不会影响其他测试的执行。
下一篇:不同的数组初始化方式