安裝
首先依然是官方位址https://github.com/google/googletest
本文采用的版本https://github.com/google/googletest/archive/release-1.8.0.zip
本文采用的是Visual Studio Community 2017(微軟官方可以免費下載下傳,無需CDKEY,也沒有任何功能限制)
googletest已經弄好了CMAKE。是以,主流的開發環境,比如QT,CODEBLOCK都是可以一步搞定。
cmake 最終生成gtest.sln,編譯生成gtest.lib和gtest_main.lib(注意MTD 和MDD要和使用的工程保持一緻)
include目錄就是zip下的include目錄
使用
假設我們有這麼個函數
int Factorial(int n) {
int result = ;
for (int i = ; i <= n; i++) {
result *= i;
}
//無數代碼
return result;
}
編寫兩個測試函數
// Tests factorial of 0.
TEST(CaseTest1, HandlesZeroInput) {
EXPECT_EQ(, Factorial());
}
// Tests factorial of positive numbers.
TEST(CaseTest2, HandlesPositiveInput) {
EXPECT_EQ(, Factorial());
EXPECT_EQ(, Factorial());
EXPECT_EQ(, Factorial());
EXPECT_EQ(, Factorial());
}
}
最後就是主函數
void main(int argc, char* argv[])
{
std::cout << "hello world" << std::endl;
testing::InitGoogleTest(&argc, argv);
//::testing::GTEST_FLAG(filter) = "CaseTest1*";//如果隻想測試一個函數可以把注釋放開,也可以直接在控制台參數加上--gtest_filter=CaseTest1*
RUN_ALL_TESTS();
std::cout << "hello world next time" << std::endl;
int kk;
std::cin >> kk;
}
使用說明一
測試代碼分為兩種
EXPECT_* 代表非緻命的錯誤。這個測試函數會繼續走下去(當然,如果你自己的函數出現了異常。一樣是會退出的)
ASSERT_* 代表緻命錯誤,一旦出現,這個測試函數就直接終止了
這裡的* 有TRUE ,FALSE,EQ, NE ,LT,LE ,GT,GE,八種用法,分别代表。正确,錯誤,相等,不相等,小于,小于等于,大于,大于等于
另外*還有字元串的幾種用法,如,STREQ,STRNE,STRCASEEQ,STRCASENE後面2種代表忽略大小寫
一旦發生錯誤,可以添加自己的列印,如
EXPECT_EQ(x[i], y[i]) << “Vectors x and y differ at index ” << i;
使用說明二
如果你有很多個測試樣例共用一些資料。那就需要繼承一個類
TEST函數也要改成TEST_F 。同時第一個參數也變成了該類名
// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
FooTest() {
// You can do set-up work for each test here.
}
virtual ~FooTest() {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
q0_.push_back();
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case for Foo.
std::vector<int> q0_;
};
TEST_F(FooTest, MethodBarDoesAbc) {
EXPECT_EQ(, Factorial(q0_[]));
}