目录
Catch2库是C++的一个测试开源库,这个测试框架有个很好的特性,它可以通过单个头库包含在项目中进行测试,这使得编译和更新框架特别容易。Catch2简单易用,只需一个catch.hpp即可(注意是single_include下的catch.hpp文件),可参考文档:Catch2/why-catch.md at devel · catchorg/Catch2 · GitHub
一、Catch2库简单知识
详细文档可参考C++ 测试库 Catch2 入门教程,本文只列出用到的几个宏。
1.CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
CATCH_CONFIG_MAIN宏强制Catch在当前编译单元中创建 main(),这个宏只能出现在一个CPP文件中,因为一个项目只能有一个有效的main函数。
2.TEST_CASE
这个宏可以包含一个或者两个参数,其中第一个参数是字符串格式的测试名(必须唯一),另一个参数则包含一个或多个标签(字符串格式,需要放在[]内部)。我们在这个宏内部写测试用例。可以通过标签,甚至是组合了多个标签的表达式来选择(用于运行或仅用于列出)测试用例。如手动运行下方的测试用例时,可以在exe后方加入tag值:xxx.exe [short]
TEST_CASE("Sum of integers for a short vector","[short]")
{
//...
}
3.REQUIRE
REQUIRE 是断言宏,当失败时停止测试。
TEST_CASE("Sum of integers for a short vector","[short]")
{
auto integers={1,2,3,4,5};
REQUIRE(sum_integers(integers)==15);
}
二、Catch2与CMake结合使用
我们在CMake I 创建一个简单的单元测试的基础上修改代码。
1.测试代码
//test.cpp
#include "sum_integers.h"
#include <vector>
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
TEST_CASE("Sum of integers for a short vector","[short]")
{
auto integers={1,2,3,4,5};
REQUIRE(sum_integers(integers)==15);
}
TEST_CASE("Sum of integers for a longer vector","[long]")
{
std::vector<int> integers;
for(int i=1;i<1001;i++)
{
integers.push_back(i);
}
REQUIRE(sum_integers(integers)==500500);
}
2.CMakeLists.txt
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(testUnit LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
#库
add_library(sum_integers sum_integers.cpp)
#demo
add_executable(mydemo MyDemo.cpp)
target_link_libraries(mydemo sum_integers)
#test
add_executable(mytest test.cpp)
target_link_libraries(mytest sum_integers)
enable_testing()
#注意这里
add_test(
NAME catch_test
COMMAND $<TARGET_FILE:mytest> --success
)
我们在命令行中添加了success参数,这是Catch2库支持的,表示测试成功时也会有输出。