gtest glog
a.h:
1 int fun(int a);
a.cpp:
#include"a.h" int fun(int a) { return a; }
h.cpp:
#include"glog/logging.h" #include<gmock/gmock.h> #include<iostream> #include"a.h" using namespace std; //using namespace CodeMood; TEST(A,B) { EXPECT_EQ(1,fun(1)); } int main(int argc,char** argv) { testing::InitGoogleMock(&argc,argv); google::InitGoogleLogging(argv[0]); RUN_ALL_TESTS(); FLAGS_log_dir="./log"; LOG(INFO)<<"hello glog"; LOG(INFO)<<"MIAO"; return 0; }
makefile:
a:a.o h.o g++ -o a a.o h.o -lglog -lgmock -lpthread a.o:a.cpp g++ -c a.cpp h.o:h.cpp a.h g++ -c h.cpp clean: rm -rv a.o h.o a
gtest
functions.h
#ifndef _FUNCTIONS_H #define _FUNCTIONS_H int add(int one,int two); int myMinus(int one,int two); int multiply(int one,int two); int divide(int one,int two); #endif
functions.cpp
#include "functions.h" int add(int one,int two){ return one+two; } int myMinus(int one,int two){ return one-two; } int multiply(int one,int two){ return one*two; } int divide(int one,int two){ return one/two; }
functionsTest.cpp
#include <gtest/gtest.h> #include "functions.h" TEST(AddTest,AddTestCase){ ASSERT_EQ(2,add(1,1)); } TEST(MinusTest,MinusTestCase){ ASSERT_EQ(10,myMinus(25,15)); } TEST(MultiplyTest,MutilplyTestCase){ ASSERT_EQ(12,multiply(3,4)); } TEST(DivideTest,DivideTestCase){ ASSERT_EQ(2,divide(7,7)); }
TestAll.cpp
#include <gtest/gtest.h> #include <iostream> using namespace std; int main(int argc,char* argv[]) { //testing::GTEST_FLAG(output) = "xml:"; //若要生成xml结果文件 testing::InitGoogleTest(&argc,argv); //初始化 RUN_ALL_TESTS(); //跑单元测试 return 0; }
这里单独初始化gtest然后执行也可以实现测试,具体原理有待研究
g++ -c functions.cpp
g++ -c functionsTest.cpp
g++ -c TestAll.cpp
g++ -o main functions.o functionsTest.o TestAll.o -lpthread -lgmock -lglog
这里我用-lgmock代替了-lgtest,因为gmock包含了gtest。至于为嘛要加-lpthread。。反正不加就会错,据说是因为编译过程会用到线程相关。。有待考证
gmock
interface.h
namespace seamless { class interface { public: virtual ~interface(){} public: virtual int getid(int index)=0; }; }
mock.h
#include<gmock/gmock.h> #include"interface.h" namespace seamless { class mock:public interface { public: MOCK_METHOD1(getid,int(int a)); }; }
test.c
#include<gmock/gmock.h> #include<iostream> #include<cstdlib> #include"mock.h" using namespace seamless; using namespace std; using ::testing::Return; int main(int argc,char** argv) { testing::InitGoogleMock(&argc,argv); int testnum=3; mock m; EXPECT_CALL(m,getid(2)).Times(1).WillOnce(Return(testnum)); int result=m.getid(2); cout<<result<<endl; return EXIT_SUCCESS; }
g++ -o test test.c -lpthread -lgtest