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.