【单元测试】C/C++单元测试

引言

测试C++程序时,我们通常会在意两件事:

  1. 运行结果是否正确?
  2. 是否发生了内存泄漏?

第一件事所有编程语言都需要在意,通常是给程序各种输入,检验输出的正确性,Catch是一个轻巧的单元测试框架,学习起来非常容易;
第二件事应该是C/C++独有的,需要跟踪运行时动态分配的内存,虽然可以自行重载new/delete运算符做到这一点,但Valgrind可以为我们检测绝大多数内存相关问题(包括内存泄漏、数组越界、使用未初始化变量等)。


链接:https://www.jianshu.com/p/6f03a0cfe60c
 

选择Catch的原因

比gtest简单,单文件,少配置。

使用方法

第一步,下载Catch的单一头文件Catch.hpp
第二步,把Catch.hpp放到工程目录下(确保能正确include即可)。

试用例子

编写Trie

正好刷Leetcode写到了Trie,就修改一下拿它做例子,不感兴趣可以直接跳到第三节Catch的使用方法。

Trie又叫字典树、前缀树(prefix tree),是一种用来实现快速检索的多叉树。简单地讲,从根节点出发经过的路径确定了一个字符串,每个节点有标记当前字符串是否为有效单词。比如记当前字符串为s,走ten那条路径的话:

  1. 选择"t",s从“”变成“t”,不是有效单词;
  2. 选择“e”,s从“t”变成“te”,不是有效单词;
  3. 选择“n”,s从“te”变成“ten”,是有效单词。

Trie示意图,盗自wiki

首先来看Trie中节点TrieNode的定义:

typedef struct TrieNode {
    bool completed;
    std::map<char, TrieNode *> children;
    TrieNode() : completed(false) {};
} TrieNode;

TrieNode用bool值completed标记当前字符串是否为有效单词,用children实现字符到后继TrieNode的映射。比如上图的根节点,children里就会有“t”、“A”、“i”三项。

然后来看Trie的定义:

class Trie {
    public:
        Trie(void);
        ~Trie(void);
        void insert(std::string word);
        bool search(std::string word);
    private:
        TrieNode *root;
};

含义非常清楚,除去构造和析构函数外,insert用于把单词加入Trie,search用于查找单词是否在Trie中。
Trie的具体实现放在我github上的DSAF里,这里直奔主题不再赘述。

使用Catch

话不多说,直接看使用Catch的测试文件test.cpp:

#include <iostream>
#include <cstdlib>

#include "Trie.h"

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

using namespace std;

TEST_CASE("Testing Trie") {
    // set up
    Trie *t = new Trie();

    // different sections
    SECTION("Search an existent word.") {
        string word = "abandon";
        t->insert(word);
        REQUIRE(t->search(word) == true);
    }
    SECTION("Search a nonexistent word.") {
        string word = "abandon";
        REQUIRE(t->search(word) == false);
    }

    // tear down
    delete t;
}

除去trivial的#include "catch.hpp"外,使用#define CATCH_CONFIG_MAIN表示让Catch自动提供main函数,运行在TEST_CASE中设计的测试。

简单地讲,每个TEST_CASE由三部分组成,set up、sections和tear down,set up是各个section都需要的准备工作,tear down是各个section都需要的清理工作,set up和tear down对于每个section都会执行一遍

比如有一个TEST_CASE:

TEST_CASE {
    set up
    case 1
    case 2
    tear down
}

真正执行时就是:set up->case 1->tear down->set up->case 2->tear down。

此处TEST_CASE里的两个section,第一个section是查找Trie中存在的单词,第二个section是查找Trie中不存在的单词。REQUIRE是Catch提供的宏,相当于assert,检验表达式是否成立。

写好Makefile文件:

HDRS = $(wildcard *.h)
SRCS = $(wildcard *.cpp)
OBJS = $(patsubst %.cpp, %.o, $(SRCS))
DEPS = $(patsubst %.cpp, %.d, $(SRCS))

TARGET = test
CXX = g++

$(TARGET): $(OBJS)
    $(CXX) -g -o $(TARGET) $(OBJS)

-include $(DEPS)

%.o: %.cpp
    $(CXX) -c -MMD -std=c++11 $<

.PHONY: clean

clean:
    -rm *.o
    -rm *.d
    -rm *.gch
    -rm $(TARGET)

 make之后运行test,可以看到:

修改search方法,使得总是返回true,那么第一个section仍然正确,第二个section出错:

Catch告诉我们在第二个section,也就是“Search a nonexistent word”时出错,失败的原因是实际search结果为true。

转自:https://www.jianshu.com/p/6f03a0cfe60c

猜你喜欢

转载自blog.csdn.net/bandaoyu/article/details/91359656