是什么 ? | : | a Unit Testing Framework for C. |
开发语言 | : | C |
官方主页 | : | http://cunit.sourceforge.net |
源码仓库 | : | https://gitlab.com/cunity/cunit |
操作系统 | 包管理器 | 安装命令 |
---|---|---|
All | vcpkg | vcpkg install cunit vcpkg install cunit:x64-osx vcpkg install cunit:x64-linux vcpkg install cunit:x64-windows |
macOS | HomeBrew | brew install cunit |
GNU/Linux | HomeBrew | brew install cunit |
apt | sudo apt-get install -y cunit | |
CentOS | yum | sudo yum install -y cunit |
dnf | sudo dnf install -y cunit | |
openSUSE | zypper | sudo zypper install -y cunit |
Alpine Linux | apk | sudo apk add cunit |
pacman | sudo pacman -Syyu --noconfirm | |
Gentoo Linux | Portage | sudo emerge cunit |
需求:编写一个四则运算
中的加法运算
的实现,并使用CUnit
进行单元测试。
设计:工程结构如下
add
└── src
├── include
│ └── add.h
├── lib
│ └── add.c
└── test
└── add.c
CUnit
step1、编写src/include/add.h
#ifndef ADD_H
#define ADD_H
int add(int a, int b);
#endif
step2、编写src/lib/add.c
#include <add.h>
int add(int a, int b) {
return a + b;
}
step3、编写src/test/add.c
#include <CUnit/CUnit.h>
#include <CUnit/Basic.h>
#include <add.h>
void test_add() {
CU_ASSERT_EQUAL(add(0, 0), 0);
CU_ASSERT_EQUAL(add(0, 1), 1);
CU_ASSERT_EQUAL(add(1, 0), 1);
CU_ASSERT_EQUAL(add(1, -1), 0);
}
// http://cunit.sourceforge.net/example.html
int main() {
/* initialize the CUnit test registry */
if (CUE_SUCCESS != CU_initialize_registry()) {
return CU_get_error();
}
/* add a suite to the registry */
CU_pSuite pSuite = CU_add_suite("Suite_1", NULL, NULL);
if (NULL == pSuite) goto cleanup;
/* add the tests to the suite */
if (NULL == CU_add_test(pSuite, "test add()", test_add)) goto cleanup;
CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests();
cleanup:
CU_cleanup_registry();
return CU_get_error();
}
step4、使用cc命令编译单元测试程序
cc -o add-test -Isrc/include -lcunit src/test/add.c src/lib/add.c
step5、运行单元测试程序
./add-test
运行效果如下: