使用catch做单元测试简介

Posted stultz-lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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 );
}

以上是关于使用catch做单元测试简介的主要内容,如果未能解决你的问题,请参考以下文章

spring有使用catch做逻辑判断

Promise.catch() 不会在 AngularJS 单元测试中捕获异常

Nodejs/NestJS ExceptionFilter Catch 方法的 Jest 单元测试

单元测试 Nest JS 过滤器捕获方法

高手如何给 Spring MVC 做单元测试?

模拟无效方法的try catch块并使用EasyMock或Mockito捕获异常