使用gtest进行C代码单元测试
平台/工具
- gtest版本:1.10.0
- 测试环境:Ubuntu16.04
- 编译工具:g++ 5.4.0
测试代码
// sort.h
#ifndef SORT_H
#define SORT_H
extern void insertion_sort(int* A, int n);
extern void insertion_down_sort(int* A, int n);
#endif
// sort.c
#include "sort.h"
void insertion_sort(int* A, int n) {
int j;
for (j = 1; j < n; j++) {
int key = A[j];
int i = j - 1;
while (i >= 0 && A[i] > key) {
A[i + 1] = A[i];
i--;
}
A[i + 1] = key;
}
}
void insertion_down_sort(int* A, int n) {
int j;
for (j = 1; j < n; j++) {
int key = A[j];
int i = j - 1;
while (i >= 0 && A[i] < key) {
A[i + 1] = A[i];
i--;
}
A[i + 1] = key;
}
}
// 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();
}
// sort_test.cc
#include <gtest/gtest.h>
extern "C" {
#include "sort.h"
}
TEST(sort, insertion_sort_1) {
int A[] = {5,2,4,6,1,3};
int B[] = {1,2,3,4,5,6};
insertion_sort(A, 6);
for (int i = 0; i < 6; i++)
EXPECT_EQ(A[i], B[i]);
}
TEST(sort, insertion_sort_2) {
int A[] = {52,23,44,64,21,23};
int B[] = {21,23,23,44,52,64};
insertion_sort(A, 6);
for (int i = 0; i < 6; i++)
EXPECT_EQ(A[i], B[i]);
}
TEST(sort, insertion_down_sort_1) {
int A[] = {5,2,4,6,1,3};
int B[] = {6,5,4,3,2,1};
insertion_down_sort(A, 6);
for (int i = 0; i < 6; i++)
EXPECT_EQ(A[i], B[i]);
}
命令行编译流程
- 编译googtest
直接引用github上的md文件 -> googletest
git clone https://github.com/google/googletest.git -b release-1.10.0
cd googletest # Main directory of the cloned repository.
mkdir build # Create a directory to hold the build output.
cd build
cmake .. # Generate native build scripts for GoogleTest.
make
make install
- 编译
~/gtest_demo$ ls
main.cc sort.c sort.h sort_test.cc
gcc -o sort.o -c sort.c # 源代码
g++ -std=c++11 -o main.o -c main.cc -lgtest -lpthread # gtest入口
g++ -std=c++11 -o sort_test.o -c sort_test.cc -lpthread -lgtest # gtest测试文件
g++ -std=c++11 -o main *.o -lgtest -lpthread # 链接生成测试文件
- 运行
~/gtest_demo$ ./main
[==========] Running 3 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 3 tests from sort
[ RUN ] sort.insertion_sort_1
[ OK ] sort.insertion_sort_1 (0 ms)
[ RUN ] sort.insertion_sort_2
[ OK ] sort.insertion_sort_2 (0 ms)
[ RUN ] sort.insertion_down_sort_1
[ OK ] sort.insertion_down_sort_1 (0 ms)
[----------] 3 tests from sort (1 ms total)
[----------] Global test environment tear-down
[==========] 3 tests from 1 test suite ran. (1 ms total)
[ PASSED ] 3 tests.
Makfile
如果要将gtest集成到项目代码里,可以在gtest里写一个Makefile,提高自动化程度。
具体的示例代码见:gtest_demo