一.用 TEST() 宏声明测试函数
TEST(name1, name2)
{
EXPECT_EQ(value1, value2);
}
name1:测试用例名称 类名 文件名
name2:测试名称 方法名 函数名
二.初始化 googletest 并运行所有测试
int main(intargc,char** argv)
{
::testing::InitGoogleTest(&argc, argv);
returnRUN_ALL_TESTS();
}
InitGoogleTest会初始化一些环境变量,RUN_ALL_TESTS()会调用所有的TEST(name1, name2)
编译时链接-lgtest -lpthread
ASSERT_* 版本的断言失败时会产生致命失败,并结束当前函数;
EXPECT_* 版本的断言失败时产生非致命失败,但不会中止当前函数。
例子
- // Configure.h
- #pragma once
- #include <string>
- #include <vector>
- class Configure
- {
- private:
- std::vector<std::string> vItems;
- public:
- int addItem(std::string str);
- std::string getItem(int index);
- int getSize();
- };
- // Configure.cpp
- #include "Configure.h"
- #include <algorithm>
- /**
- * @brief Add an item to configuration store. Duplicate item will be ignored
- * @param str item to be stored
- * @return the index of added configuration item
- */
- int Configure::addItem(std::string str)
- {
- std::vector<std::string>::const_iterator vi=std::find(vItems.begin(), vItems.end(), str);
- if (vi != vItems.end())
- return vi - vItems.begin();
- vItems.push_back(str);
- return vItems.size() - 1;
- }
- /**
- * @brief Return the configure item at specified index.
- * If the index is out of range, "" will be returned
- * @param index the index of item
- * @return the item at specified index
- */
- std::string Configure::getItem(int index)
- {
- if (index >= vItems.size())
- return "";
- else
- return vItems.at(index);
- }
- /// Retrieve the information about how many configuration items we have had
- int Configure::getSize()
- {
- return vItems.size();
- }
- // ConfigureTest.cpp
- #include <gtest/gtest.h>
- #include "Configure.h"
- TEST(ConfigureTest, addItem)
- {
- // do some initialization
- Configure* pc = new Configure();
- // validate the pointer is not null
- ASSERT_TRUE(pc != NULL);
- // call the method we want to test
- pc->addItem("A");
- pc->addItem("B");
- pc->addItem("A");
- // validate the result after operation
- EXPECT_EQ(pc->getSize(), 2);
- EXPECT_STREQ(pc->getItem(0).c_str(), "A");
- EXPECT_STREQ(pc->getItem(1).c_str(), "B");
- EXPECT_STREQ(pc->getItem(10).c_str(), "");
- delete pc;
- }
- #include <gtest/gtest.h>
- int main(int argc, char** argv) {
- testing::InitGoogleTest(&argc, argv);
- // Runs all tests using Google Test.
- return RUN_ALL_TESTS();
- }
g++ -c configure.cpp -lgtest -lpthread -L /usr/local/webserver/gtest/lib -I /usr/local/webserver/gtest/include
g++ -c configuretest.cpp -lgtest -lpthread -L /usr/local/webserver/gtest/lib -I /usr/local/webserver/gtest/include
g++ -c main.cpp -lgtest -lpthread -L /usr/local/webserver/gtest/lib -I /usr/local/webserver/gtest/include
g++ -o app main.o configure.o -lgtest -lpthread -L /usr/local/webserver/gtest/lib -I /usr/local/webserver/gtest/include