CMake I 使用Catch2库进行单元测试

目录

一、Catch2库简单知识

1.CATCH_CONFIG_MAIN

2.TEST_CASE

3.REQUIRE

二、Catch2与CMake结合使用

1.测试代码

2.CMakeLists.txt

三、配置、构建与测试

1.配置

 2.构建

3.测试 


        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库支持的,表示测试成功时也会有输出。

三、配置、构建与测试

1.配置

 2.构建

3.测试 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烫青菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值