GTest入门demo

本文展示了如何使用C++编写简单的数学运算函数,并利用Google Test框架创建和执行单元测试,确保代码的正确性。通过编译及链接步骤,成功运行测试用例并验证了加法和减法函数的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1.源码文件如下

arithmetic.c

#include "arithmetic.h"

int add(int a, int b) {
    return a + b;
}

int sub(int a, int b) {
    return a - b;
}

arithmetic.h

#ifndef ARITHMETIC_H
#define ARITHMETIC_H

extern int add(int a, int b);
extern int sub(int a, int b);

#endif

2.测试用例如下

arithmetic_test.cc

#include <gtest/gtest.h>

extern "C" {
#include "arithmetic.h"
}

TEST(arithmetic, add_test) {
    int a = 2;
    int b = 3;

    int sum = add(a, b);

    EXPECT_EQ(a + b , sum);
}

TEST(arithmetic, sub_test) {
    int a = 2;
    int b = 3;

    int sum = sub(a, b);

    EXPECT_EQ(a - b , sum);
}

 3.测试入口

main.cc

#include <gtest/gtest.h>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {

	testing::InitGoogleTest(&argc, argv);
    
	return RUN_ALL_TESTS();
}

4.编译测试

把上述.cc文件先编译成.o文件,然后整合成可执行脚本

gcc -o arithmetic.o -c arithmetic.c
g++ -std=c++11 -o main.o -c main.cc -lgtest -lpthread
g++ -std=c++11 -o arithmetic_test.o -c arithmetic_test.cc -lgtest -lpthread
g++ -std=c++11 -o main *.o -lgtest -lpthread

5.执行

user@PC:~/gtest_demo$ ./main
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from arithmetic
[ RUN      ] arithmetic.add_test
[       OK ] arithmetic.add_test (0 ms)
[ RUN      ] arithmetic.sub_test
[       OK ] arithmetic.sub_test (0 ms)
[----------] 2 tests from arithmetic (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test suite ran. (0 ms total)
[  PASSED  ] 2 tests.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值