Catch2是一个C++单元测试框架。话说C++已经有那么测试框架了,为什么还要再创一个新的框架呢? 在Why do we need yet another C++ test framework?作者有所解释。不过我个人的感觉是其他C++单元测试框架大都偏xUnit风格,就是Setup/Teardown那一套,并不是所有人都喜欢。

个人对Catch2的感觉是比较小清新,采用的C++11,整体上比较新潮。另外最近测试界流行了一个新的风格,叫做BDD(Behaviour Driven Development),好像从Ruby开始吹的。Catch2也可以支持这种风格。

Catch2的教程中的例子来看一眼Catch2的风格:

#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#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( "resizing bigger changes size and capacity" ) {
        v.resize( 10 );

        REQUIRE( v.size() == 10 );
        REQUIRE( v.capacity() >= 10 );
    }
    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 );
    }
}

Catch2的测试用例是通过TEST_CASE和SECTION组织的。一个TEST_CASE可以嵌套多个子SECTION,每个SECTION还可以嵌套其他SECTION。SECTION就像是一棵树的分支,可以有多层。关键是,运行每个TEST_CASE的时候,每个SECTION都会被运行一遍,而且是从最顶层的分支开始运行。所以层级越高的代码会被运行越多次。所以Setup/Teardown代码可以写在上一层SECTION里面。

一些特点

Catch2提供了一个main函数,可以通过下面的方式来使用。

#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"

(Supplying your own main())[https://github.com/catchorg/Catch2/blob/master/docs/own-main.md#top]告诉你如何自定义这个main函数。

Catch2提供的main函数使用了Clara作为命令行参数解析工具,看起来挺好用的。Clara好像不维护了,可以看看Lyra

其他特性可以参考Reference

(本篇完)

2020-12-26更新

通过Test Adapter for Catch2可以在VS2019中的TestExplorer支持Catch2的测试用例。但是需要配置一个.runsettings文件才能工作,具体参考Documentation for Test Adapter for Catch2

另一个参考Best practices for Unit testing with Catch2 in Visual Studio

关于VS2019的参考,在Configure unit tests by using a .runsettings file

(更新完)