1. GoogleTest 安裝, 基于gtest V1.10
git clone https://github.com/google/googletest
cd googletest
cmake CMakeLists.txt
make
sudo cp lib/lib*.a /usr/lib
sudo cp –a googletest/include/gtest /usr/include
sudo cp –a googlemock/include/gmock /usr/include
2. 用法小結
2.1 簡單測試安裝
#include<gtest/gtest.h>
int add(int a,int b){
return a+b;
}
TEST(testCase,test0){
EXPECT_EQ(add(2,3),5);
}
int main(int argc,char **argv){
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
2.2 系統測試
#include <iostream>
#include <gtest/gtest.h>
using namespace std;
class Student {
public:
Student() : age_(0){}
Student(int a): age_(a){}
void print() {
cout << "*******"<<age_<<"*********"<<endl;
}
private:
int age_;
};
class FooEnviroment : public testing::Environment {
public:
virtual void SetUp() {
cout << "Foo FooEnvironment SetUp" << endl;
}
virtual void TearDown() {
cout << "Foo FooEnviroment TearDown" << endl;
}
};
class TestMap : public testing::Test {
public:
void SetUp() override {
cout << "Call TestMap SetUp functions." << endl;
}
void TearDown() override {
cout << "Call TestMap TearDown functions." << endl;
}
static void SetUpTestSuite() {
cout << "Call TestMap SetUpTestSuite." << endl;
}
static void TearDownTestSuite() {
cout << "Call TestMap TearDownTestSuite." << endl;
}
void Print() {
s_.print();
}
private:
Student s_;
};
TEST_F(TestMap, Test1) {
cout << "Test1 starts" << endl;
Print();
}
TEST_F(TestMap, Test2) {
cout << "Test2 starts" << endl;
Print();
}
int main(int argc, char * argv[]) {
testing::AddGlobalTestEnvironment(new FooEnviroment);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
輸出結果
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
Foo FooEnvironment SetUp
[----------] 2 tests from TestMap
Call TestMap SetUpTestSuite.
[ RUN ] TestMap.Test1
Call TestMap SetUp functions.
Test1 starts
*******0*********
Call TestMap TearDown functions.
[ OK ] TestMap.Test1 (0 ms)
[ RUN ] TestMap.Test2
Call TestMap SetUp functions.
Test2 starts
*******0*********
Call TestMap TearDown functions.
[ OK ] TestMap.Test2 (0 ms)
Call TestMap TearDownTestSuite.
[----------] 2 tests from TestMap (0 ms total)
[----------] Global test environment tear-down
Foo FooEnviroment TearDown
[==========] 2 tests from 1 test suite ran. (1 ms total)
[ PASSED ] 2 tests.