catch2: 测试框架

警告
本文最后更新于 2020-10-19,文中内容可能已过时。

catch2 是一个可扩展性非常高的测试框架。

安装

Demo

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* @Author: "william"
* @Date:   2020-10-19 17:21:32
* @Last Modified by:   "william"
* @Last Modified time: 2020-10-19 17:29:18
*/
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

int main( int argc, char *argv[])
{
    int res = Catch::Session().run( argc, argv);
    return res;

    // =========================================================================
    // Catch::Session session; // There must be exactly one instance

    // int height = 0; // Some user variable you want to be able to set

    // // Build a new parser on top of Catch's
    // using namespace Catch::clara;
    // auto cli
    //   = session.cli() // Get Catch's composite command line parser
    //   | Opt( height, "height" ) // bind variable to a new option, with a hint string
    //       ["-g"]["--height"]    // the option names it will respond to
    //       ("how high?");        // description string for the help output

    // // Now pass the new composite back to Catch so it uses that
    // session.cli( cli );

    // // Let Catch (using Clara) parse the command line
    // int returnCode = session.applyCommandLine( argc, argv );
    // if( returnCode != 0 ) // Indicates a command line error
    //     return returnCode;
    // return session.run();
    // =========================================================================
}

int Factorial( int number ) {
    return number <= 1 ? number : Factorial( number - 1 ) * number;  // fail
    // return number <= 1 ? 1      : Factorial( number - 1 ) * number;  // pass
}

TEST_CASE( "Factorial of 0 is 1 (fail)", "[single-file]" ) {
    REQUIRE( Factorial(0) == 1 );
}

TEST_CASE( "Factorials of 1 and higher are computed (pass)", "[single-file]" ) {
    REQUIRE( Factorial(1) == 1 );
    REQUIRE( Factorial(2) == 2 );
    REQUIRE( Factorial(3) == 6 );
    REQUIRE( Factorial(10) == 3628800 );
}

编译

1
g++ -std=c++11 main.cpp

运行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
./a.out                                                                            [17:28:46]

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a.out is a Catch v2.13.0 host application.
Run with -? for options

-------------------------------------------------------------------------------
Factorial of 0 is 1 (fail)
-------------------------------------------------------------------------------
main.cpp:44
...............................................................................

main.cpp:45: FAILED:
  REQUIRE( Factorial(0) == 1 )
with expansion:
  0 == 1

===============================================================================
test cases: 2 | 1 passed | 1 failed
assertions: 5 | 4 passed | 1 failed

技巧

相关内容

william 支付宝支付宝
william 微信微信
0%