简介
Catch2是一个header-only测试框架。
使用说明
#define CATCH_CONFIG_MAIN // 宏定义指明main()函数
#include "catch.hpp"
// 测试用例
TEST_CASE( "vectors can be sized and resized", "[vector]" )
{
std::vector<int> v( 5 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
// 执行每一个SECTION,都会重新开始执行
SECTION( "resizing bigger changes size and capacity" )
{
v.resize( 10 );
REQUIRE( v.size() == 10 );
REQUIRE( v.capacity() >= 10 );
}
// 执行下面的SECTION时,v.size()=5
SECTION( "resizing smaller changes size but not capacity" )
{
v.resize( 0 );
REQUIRE( v.size() == 0 );
REQUIRE( v.capacity() >= 5 );
}
SECTION( "reserving bigger changes capacity but not size" )
{
v.reserve( 10 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 10 );
}
SECTION( "reserving smaller does not change size or capacity" )
{
v.reserve( 0 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
}
}
Assertion
基本断言
- REQUIRE(expression)
- CHECK(expression)
- REQUIRE_FALSE(expression)
- CHECK_FALSE(expression)
注意:REQUIRE和CHECK最主要的区别在于REQUIRE表达式为false时中断执行,而CHECK继续执行。
Matcher比较器
- REQUIRE_THAT(lhs, matcher expression)
- CHECK_THAT(lhs, matcher expression)
主要内置Matchers
– string matchers:StartsWith, EndsWith, Contains, Equals and Matches
– vector matchers:Contains, VectorContains and Equals
– floating point matchers:WithinULP and WithinAbsREQUIRE_THAT( str, EndsWith( "as a service", Catch::CaseSensitive::No ) );
浮点数比较
- epsilon:default std::numeric_limits::epsilon()*100.
- margin:default 0.0.
- scale:default 0.0.
TEST_CASE("approx epsilon", "[single-file]")
{
// 闭区间
// [100-100*epsilon,100+100*epsilon]
Approx target = Approx(100).epsilon(0.01);
CHECK(100.0 == target); // Obviously true
CHECK(99.0 == target); // Obviously true
CHECK(98.1 == target); // Obviously true
CHECK(101.0 == target); // Obviously true
CHECK(101.1 == target); // Obviously true
}
TEST_CASE("approx margin", "[single-file]")
{
// 闭区间
// [100-margin,100+margin]
Approx target = Approx(100).margin(1);
CHECK(100.0 == target); // Obviously true
CHECK(99.0 == target); // Obviously true
CHECK(98.1 == target); // Obviously true
CHECK(101.0 == target); // Obviously true
CHECK(101.1 == target); // Obviously true
}
Logging
- INFO( message expression )
- WARN( message expression )
- FAIL( message expression )
- FAIL_CHECK( message expression )
- CAPTURE( expression1, expression2, … )
int a = 1, b = 2, c = 3;
CAPTURE( a, b, c, a + b, c > b, a == 1);
输出:
// 输出
//a: = 1
//b : = 2
//c : = 3
//a + b : = 3
//c > b : = true
//a == 1 : = true