初试gtest

Build gtest:

  1. 按照这里介绍的,安装CMake
  2. 在这里下载googletest源码压缩包,解压,进入解压后的目录
  3. mkdir build && cd build
  4. cmake .. // 这之后,build目录下会出现Makefile等文件
  5. cmake --build .// 注意不要漏掉最后的点.

之后,在build目录下会出现libgtest.a 和libgtest_main.a

使用gtest做a+b的测试:

add.h

#ifndef __ADD_H__
#define __ADD_H__

int Add(int a, int b);

#endif // __ADD_H__
add.cpp

#include "add.h"

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

main.cpp

#include <gtest/gtest.h>
#include "add.h"

TEST(AddTest, Positive)
{
	EXPECT_EQ(3, Add(1,2));
	EXPECT_EQ(5, Add(2,3));
}

TEST(AddTest, Negative)
{
	EXPECT_EQ(-3, Add(-1,-2));
	EXPECT_EQ(-5, Add(-2,-3));
}

int main(int argc, char **argv) {
	testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}
Makefile(假设gtest解压到/home/yasi/gtest-1.6.0下,则按照上面的操作,include路径在/home/yasi/gtest-1.6.0/include,lib目录是/home/yasi/gtest-1.6.0/build)

INC_OPT += -I/home/yasi/gtest-1.6.0/include 
LNK_OPT = -L/home/yasi/gtest-1.6.0/build -lgtest -lpthread
TARGET = add_test

OBJS = \
        ./add.o \
        ./main.o

$(TARGET) : $(OBJS)
	$(CXX) -o $@ $(OBJS) $(LNK_OPT)

%.o : %.cpp
	$(CXX) $(INC_OPT) -c -o $@ $< -g

clean :
	rm -f $(TARGET) *.o
build得到add_test,执行结果:

[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from AddTest
[ RUN      ] AddTest.Positive
[       OK ] AddTest.Positive (0 ms)
[ RUN      ] AddTest.Negative
[       OK ] AddTest.Negative (0 ms)
[----------] 2 tests from AddTest (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (2 ms total)
[  PASSED  ] 2 tests.

测试代码下载


你可能感兴趣的:(初试gtest)