Linux环境下C++单元测试Gtest 入门

来源:互联网 发布:mac卸载 编辑:程序博客网 时间:2024/06/08 04:11

简介

Goodtest是一款强大的C++单元测试框架,可以在Linux,Windows上等多种平台上互动

可以在这里下载:https://github.com/google/googletest然后按照教程进行配置就可以了

ASSERT_*是fatal判断,一旦为false,程序将终止,还可能发生内存泄漏

EXPECT_*为false后测试程序会输出相关信息,并继续运行

用户自定义的类如果要进行比较,需要实现操作符

ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";//通过这种方式可以自定义用户输出for (int i = 0; i < x.size(); ++i) {  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;}


一、编码

在同一个文件夹下编写以下三个文件:

//file sqrt.h#pragma onceint sqrt(int x);

//file sqrt.cpp#include "sqrt.h"int sqrt(int x){if (x<=0){return 0;}if (x==1){return 1;}int small = 0;int large = x;int temp = x / 2;while (small<large){int a = x / temp;int b = x / (temp + 1);if (a==temp){return a;}if (b==temp+1){return b;}if (temp<a&&temp+1>b){return temp;}else if(temp<a&&temp+1<b){small = temp + 1;temp = (small + large) / 2;}else{large = temp;temp = (small + large) / 2;}}return -1;}
//file sqrt_unittest.cpp#include"sqrt.h"#include<gtest/gtest.h>TEST(SQRTest, Zero){EXPECT_EQ(0, sqrt(0));}TEST(SQRTTest, Positive){EXPECT_EQ(100, sqrt(10000));}
二、编写makefile

注意,在连接阶段要-L -l连接静态gtest库

objects = sqrt.o sqrt_unittest.orunTest : $(objects)g++ - o runTest $(objects) - L / usr / lib / -lgtest_main - lpthreadsqrt.o : sqrt.cpp sqrt.hg++ - c sqrt.cppsqrt_unittest.o : sqrt_unittest.cppg++ - c sqrt_unittest.cppclean :rm runTest $(objects)

三、编译链接运行




原创粉丝点击