Linux环境下C++单元测试Gtest 入门
Linux环境下C++单元测试Gtest 入门
简介
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 once
int 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
{
int a = x / temp;
int b = x / (temp + 1);
if (a==temp)
{
return a;
}
if (b==temp+1)
{
return b;
}
if (tempb)
{
return temp;
}
else if(temp
{
small = temp + 1;
temp = (small + large) / 2;
}
else
{
large = temp;
temp = (small + large) / 2;
}
}
return -1;
}
//file sqrt_unittest.cpp
#include"sqrt.h"
#include
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.o
runTest : $(objects)
g++ - o runTest $(objects) - L / usr / lib / -lgtest_main - lpthread
sqrt.o : sqrt.cpp sqrt.h
g++ - c sqrt.cpp
sqrt_unittest.o : sqrt_unittest.cpp
g++ - c sqrt_unittest.cpp
clean :
rm runTest $(objects)
三、编译链接运行
Linux环境下C++单元测试Gtest 入门相关教程