catch单元测试简明例子

简单研究了下catch,做了一个例子,说下遇到的坑点

先说本文重点,遇到一个坑就是SECTION()里面必须写东西,否则编译不通过

然后,catch用法

  1. 从官网下载catch.hpp文件放到你和你想要测试的文件同一目录下
  2. 编写test文件(c/cc都可)

例子1

这个文件官网给的例子,是单独在一个文件内的

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

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

TEST_CASE( "Factorials are computed", "[factorial]" ) {

    //section里面必须写东西
    SECTION("test a"){
        //这个会报错,测试不通过
        REQUIRE( Factorial(0) == 1 );
        //下面的测试都会通过
        REQUIRE( Factorial(1) == 1 );
        REQUIRE( Factorial(2) == 2 );
        REQUIRE( Factorial(3) == 6 );
        REQUIRE( Factorial(10) == 3628800 );
    }
    
}

这个文件名是Demo.cc,所以编译命令如下

g++ Demo.cc -o demo

例子2

例子2是自己写的一个小的测试用例,和官网给的例子不同的是测试文件和被测试文件不在同一文件内

首先,被测试文件 find.cc

#include "find.h"

A::A(){}
A::~A(){}

bool A::find(int n){
    if(n == 1)
        return true;
}

find.h

class A{
public:
    A();
    ~A();
    bool find(int n);
};

测试文件 Demo2.cc

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

TEST_CASE("hahaha") {
    A *a = new A();

    SECTION("test a"){
        REQUIRE( a->find(1) == true );
    }

    delete a;
}

编译命令

g++ Demo2.cc find.cc -o demo2

要点

说下测试文件的执行顺序

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

TEST_CASE("hahaha") {
    // set up
    A *a = new A();
	
    // different sections
    SECTION("section 1"){
        REQUIRE( a->find(1) == true );
    }
    SECTION("section 2"){
        //这个测试不会通过
        REQUIRE( a->find(0) == true );
    }
	
    // tear down
    delete a;
}

就这个测试文件来说,两个SECTION是不会顺序执行的,正确的执行顺序是

set up->section1->tear down->set up->section2->tear down

猜你喜欢

转载自blog.csdn.net/qq_24889575/article/details/82873379