zoukankan      html  css  js  c++  java
  • 使用catch做单元测试简介

    开始使用catch呢!

    catch的好处是,它只有一个头文件,
    坏处是,它需要C++11,不过不是很坏。

    catch有两种测试用例的书写方式:

    Normal

    unsigned int Factorial( unsigned int number ) {
        return number < 1 ? 1 : Factorial(number-1)*number;
    }
    
    TEST_CASE( "Factorials are computed", "[factorial]" ) {
    	REQUIRE( Factorial(0) == 1 );
        REQUIRE( Factorial(1) == 1 );
        REQUIRE( Factorial(2) == 2 );
        REQUIRE( Factorial(3) == 6 );
        REQUIRE( Factorial(10) == 3628800 );
    }
    

    BBD

    SCENARIO, GIVEN, WHEN and THEN macros, which map on to TEST_CASEs and SECTIONs, respectively

    SCENARIO( "vectors can be sized and resized", "[vector]" ) {
    
        GIVEN( "A vector with some items" ) {
            std::vector<int> 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 );
                }
            }
        }
    }
    
    

    最佳实践

    将catch宏和头文件用一个单独的main文件包含,避免编译时的时间浪费;

    // tests-main.cpp
    #define CATCH_CONFIG_MAIN
    #include "catch.hpp"
    
    // tests-factorial.cpp
    #include "catch.hpp"
    
    #include "factorial.h"
    
    TEST_CASE( "Factorials are computed", "[factorial]" ) {
        REQUIRE( Factorial(1) == 1 );
        REQUIRE( Factorial(2) == 2 );
        REQUIRE( Factorial(3) == 6 );
        REQUIRE( Factorial(10) == 3628800 );
    }
    
    
  • 相关阅读:
    Linux下安装maven
    非连续性及反脆弱
    高手是怎么练成的
    思维型大脑
    编写文档五轮模式
    Nginx初识
    ida快捷键
    ida+gdb调试任意平台
    gcc常用命令使用
    ida调试ios应用
  • 原文地址:https://www.cnblogs.com/Stultz-Lee/p/10089081.html
Copyright © 2011-2022 走看看