抓住

Catch 是一個僅限標題的庫,允許你同時使用 TDDBDD 單元測試樣式。

以下程式碼段來自此連結的 Catch 文件頁面 :

SCENARIO( "vectors can be sized and resized", "[vector]" ) {
    GIVEN( "A vector with some items" ) {
        std::vector v( 5 );
        
        REQUIRE( `v.size()` == 5 );
        REQUIRE( `v.capacity()` >= 5 );
        
        WHEN( "the size is increased" ) {
            v.resize( 10 );
            
            THEN( "the size and capacity change" ) {
                REQUIRE( `v.size()` == 10 );
                REQUIRE( `v.capacity()` >= 10 );
            }
        }
        WHEN( "the size is reduced" ) {
            v.resize( 0 );
            
            THEN( "the size changes but not capacity" ) {
                REQUIRE( `v.size()` == 0 );
                REQUIRE( `v.capacity()` >= 5 );
            }
        }
        WHEN( "more capacity is reserved" ) {
            v.reserve( 10 );
            
            THEN( "the capacity changes but not the size" ) {
                REQUIRE( `v.size()` == 5 );
                REQUIRE( `v.capacity()` >= 10 );
            }
        }
        WHEN( "less capacity is reserved" ) {
            v.reserve( 0 );
            
            THEN( "neither size nor capacity are changed" ) {
                REQUIRE( `v.size()` == 5 );
                REQUIRE( `v.capacity()` >= 5 );
            }
        }
    }
}

方便的是,這些測試在執行時將報告如下:

Scenario: vectors can be sized and resized
     Given: A vector with some items
      When: more capacity is reserved
      Then: the capacity changes but not the size