之后,在build目录下会出现libgtest.a 和libgtest_main.a
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) *.obuild得到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.
测试代码下载