調用測試
TEST()和TEST_F()向Google Test隱式注冊它們的測試。因此,與很多其他的C++測試框架不同,你不需要為了運行你定義的測試而將它們全部再列出來一次。
在定義好測試后,你可以通過RUN_ALL_TESTS()來運行它們,如果所有測試成功,該函數返回0,否則會返回1.注意RUN_ALL_TESTS()會運行你鏈接到的所有測試——它們可以來自不同的測試案例,甚至是來自不同的文件。
當被調用時,RUN_ALL_TESTS()宏會:
- 保存所有的Google Test標志。
- 為一個側測試創建測試固件對象。
- 調用SetUp()初始化它。
- 在固件對象上運行測試。
- 調用TearDown()清理固件。
- 刪除固件。
- 恢復所有Google Test標志的狀態。
- 重復上訴步驟,直到所有測試完成。
此外,如果第二步時,測試固件的構造函數產生一個致命錯誤,繼續執行3至5部顯然沒有必要,所以它們會被跳過。與之相似,如果第3部產生致命錯誤,第4部也會被跳過。
重要:你不能忽略掉RUN_ALL_TESTS()的返回值,否則gcc會報一個編譯錯誤。這樣設計的理由是自動化測試服務會根據測試退出返回碼來決定一個測試是否通過,而不是根據其stdout/stderr輸出;因此你的main()函數必須返回RUN_ALL_TESTS()的值。
而且,你應該只調用RUN_ALL_TESTS()一次。多次調用該函數會與Google Test的一些高階特性(如線程安全死亡測試)沖突,因而是不被支持的。
有效平臺: Linux, Windows, Mac.
編寫main()函數
你可以從下面這個樣板開始:
#include "this/package/foo.h"
#include <gtest/gtest.h>
namespace {
// 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).
}
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.
};
// Tests that the Foo::Bar() method does Abc.
TEST_F(FooTest, MethodBarDoesAbc) {
const string input_filepath = "this/package/testdata/myinputfile.dat";
const string output_filepath = "this/package/testdata/myoutputfile.dat";
Foo f;
EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
}
// Tests that Foo does Xyz.
TEST_F(FooTest, DoesXyz) {
// Exercises the Xyz feature of Foo.
}
} // namespace
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
testing::InitGoogleTest()函數負責解析命令行傳入的Google Test標志,并刪除所有它可以處理的標志。這使得用戶可以通過各種不同的標志控制一個測試程序的行為。關于這一點我們會在GTestAdvanced中講到。你必須在調用RUN_ALL_TESTS()之前調用該函數,否則就無法正確地初始化標示。
在Windows上InitGoogleTest()可以支持寬字符串,所以它也可以被用在以UNICODE模式編譯的程序中。
進階閱讀
恭喜你!你已經學到了一些Google Test基礎。你可以從編寫和運行幾個Google Test測試開始,再閱讀一下GoogleTestSamples,或是繼續研究GoogleTestAdvancedGuide,其中描述了很多更有用的Google Test特性。
已知局限
Google Test被設計為線程安全的。但是,我們還沒有時間在各種平臺上實現同步原語(synchronization primitives)。因此,目前從兩個線程同時使用Google Test斷言是不安全的。由于通常斷言是在主線程中完成的,因此在大多數測試中這都不算問題。如果你愿意幫忙,你可以試著在gtest-port.h中實現必要的同步原語。
文章來源于領測軟件測試網 http://www.kjueaiud.com/