簡介: Google 提供一種用于為 C/C++ 軟件開發單元測試的開放源碼框架,它很有意思,也很容易使用。本文介紹一些比較有用的 Google C++ Testing Framework 特性。本文基于 version 1.4。
為什么要使用 Google C++ Testing Framework?
使用這個框架有許多好理由。本節討論其中幾個。
某些類型的測試有糟糕的內存問題,這些問題只在某幾次運行期間出現。Google 的測試框架為處理這種情況提供了出色的支持??梢允褂?Google 框架重復運行相同的測試一千次。當出現故障的跡象時,自動地調用調試器。另外,這只需要在命令行上傳遞兩個開關即可實現:--gtest_repeat=1000 --gtest_break_on_failure。
與其他許多測試框架相反,可以把 Google 測試框架內置的斷言部署在禁用了異常處理(通常由于性能原因)的軟件中。因此,也可以在析構函數中安全地使用斷言。
運行測試很簡單。只需調用預定義的 RUN_ALL_TESTS 宏,而不需要通過創建或驅動單獨的運行器類來執行測試。這比 CppUnit 等框架方便多了。
只需傳遞一個開關即可生成 Extensible Markup Language (XML) 報告: --gtest_output="xml:<file name>"。在 CppUnit 和 CppTest 等框架中,需要編寫很多代碼才能生成 XML 輸出。
創建基本測試
請考慮 清單 1 所示的平方根函數的原型。
清單 1. 平方根函數的原型
double square-root (const double);
對于負數,這個例程返回 -1。正數測試和負數測試對它都有意義,所以我們編寫兩個測試。清單 2 給出測試用例。
清單 2. 平方根函數的單元測試
#include "gtest/gtest.h"
TEST (SquareRootTest, PositiveNos) {
EXPECT_EQ (18.0, square-root (324.0));
EXPECT_EQ (25.4, square-root (645.16));
EXPECT_EQ (50.3321, square-root (2533.310224));
}
TEST (SquareRootTest, ZeroAndNegativeNos) {
ASSERT_EQ (0.0, square-root (0.0));
ASSERT_EQ (-1, square-root (-22.0));
}
清單 2 創建一個名為 SquareRootTest 的測試層次結構,然后在其中添加兩個單元測試 PositiveNos 和 ZeroAndNegativeNos。TEST 是在 gtest.h(可以在下載的源代碼中找到)中定義的預定義宏,它幫助定義這個層次結構。EXPECT_EQ 和 ASSERT_EQ 也是宏 — 對于前者,即使出現測試失敗,測試仍然繼續執行;對于后者,測試終止執行。顯然,如果 0 的平方根是除 0 之外的任何數字,就沒必要再執行測試了。因此,ZeroAndNegativeNos 測試只使用 ASSERT_EQ,而 PositiveNos 測試使用 EXPECT_EQ,來報告存在多少個測試用例是平方根函數失敗而不終止測試的情況。
運行第一個測試
既然已經創建了第一個基本測試,現在就該運行它了。清單 3 是運行測試的主例程。
清單 3. 運行平方根測試
#include "gtest/gtest.h"
TEST(SquareRootTest, PositiveNos) {
EXPECT_EQ (18.0, square-root (324.0));
EXPECT_EQ (25.4, square-root (645.16));
EXPECT_EQ (50.3321, square-root (2533.310224));
}
TEST (SquareRootTest, ZeroAndNegativeNos) {
ASSERT_EQ (0.0, square-root (0.0));
ASSERT_EQ (-1, square-root (-22.0));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
顧名思義,::testing::InitGoogleTest 方法的作用就是對框架進行初始化,必須在調用 RUN_ALL_TESTS 之前調用它。在代碼中只能調用 RUN_ALL_TESTS 一次,因為多次調用會與框架的一些高級特性沖突,不支持這種做法。注意,RUN_ALL_TESTS 自動地探測并運行用 TEST 宏定義的所有測試。在默認情況下,結果輸出到標準輸出。清單 4 給出輸出。
清單 4. 運行平方根測試的輸出
Running main() from user_main.cpp
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from SquareRootTest
[ RUN ] SquareRootTest.PositiveNos
..\user_sqrt.cpp(6862): error: Value of: sqrt (2533.310224)
Actual: 50.332
Expected: 50.3321
[ FAILED ] SquareRootTest.PositiveNos (9 ms)
[ RUN ] SquareRootTest.ZeroAndNegativeNos
[ OK ] SquareRootTest.ZeroAndNegativeNos (0 ms)
[----------] 2 tests from SquareRootTest (0 ms total)
[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (10 ms total)
[ PASSED ] 1 test.
[ FAILED ] 1 test, listed below:
[ FAILED ] SquareRootTest.PositiveNos
1 FAILED TEST
Google C++ Testing Framework 的選項
在 清單 3 中,InitGoogleTest 函數接受測試基礎設施的參數。本節討論可以通過測試框架的參數實現的一些功能。
通過在命令行上傳遞 --gtest_output="xml:report.xml",可以把輸出轉儲為 XML 格式。當然,可以把 report.xml 替換為您喜歡的任何文件名。
某些測試有時候會失敗,但是在大多數時候會順利通過。這是與內存損壞相關的問題的典型特點。如果多次運行測試,就能夠提高發現失敗的可能性。如果在命令行上傳遞 --gtest_repeat=2 --gtest_break_on_failure,就重復運行相同的測試兩次。如果測試失敗,會自動調用調試器。
并不需要每次都運行所有測試,尤其是在修改的代碼只影響某幾個模塊的情況下。為了支持運行一部分測試,Google 提供 --gtest_filter=<test string>。test string 的格式是由冒號 (:) 分隔的一系列通配符模式。例如,--gtest_filter=* 運行所有測試,而 --gtest_filter=SquareRoot* 只運行 SquareRootTest 測試。如果希望只運行 SquareRootTest 中的正數單元測試,應該使用 --gtest_filter=SquareRootTest.*-SquareRootTest.Zero*。注意,SquareRootTest.* 表示屬于 SquareRootTest 的所有測試,而 -SquareRootTest.Zero* 表示不運行名稱以 Zero 開頭的測試。
清單 5 中的示例用 gtest_output、gtest_repeat 和 gtest_filter 選項運行 SquareRootTest。
清單 5. 用 gtest_output、gtest_repeat 和 gtest_filter 選項運行 SquareRootTest
[arpan@tintin] ./test_executable --gtest_output="xml:report.xml" --gtest_repeat=2 --
gtest_filter=SquareRootTest.*-SquareRootTest.Zero*
Repeating all tests (iteration 1) . . .
Note: Google Test filter = SquareRootTest.*-SquareRootTest.Z*
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from SquareRootTest
[ RUN ] SquareRootTest.PositiveNos
..\user_sqrt.cpp (6854): error: Value of: sqrt (2533.310224)
Actual: 50.332
Expected: 50.3321
[ FAILED ] SquareRootTest.PositiveNos (2 ms)
[----------] 1 test from SquareRootTest (2 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (20 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] SquareRootTest.PositiveNos
1 FAILED TEST
Repeating all tests (iteration 2) . . .
Note: Google Test filter = SquareRootTest.*-SquareRootTest.Z*
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from SquareRootTest
[ RUN ] SquareRootTest.PositiveNos
..\user_sqrt.cpp (6854): error: Value of: sqrt (2533.310224)
Actual: 50.332
Expected: 50.3321
[ FAILED ] SquareRootTest.PositiveNos (2 ms)
[----------] 1 test from SquareRootTest (2 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (20 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] SquareRootTest.PositiveNos
1 FAILED TEST
臨時禁用測試
可以臨時禁用測試嗎?可以,只需在邏輯測試名或單元測試名前面加上 DISABLE_ 前綴,它就不會執行了。清單 6 演示如何禁用 清單 2 中的 PositiveNos 測試。
清單 6. 臨時禁用測試
#include "gtest/gtest.h"
TEST (DISABLE_SquareRootTest, PositiveNos) {
EXPECT_EQ (18.0, square-root (324.0));
EXPECT_EQ (25.4, square-root (645.16));
EXPECT_EQ (50.3321, square-root (2533.310224));
}
OR
TEST (SquareRootTest, DISABLE_PositiveNos) {
EXPECT_EQ (18.0, square-root (324.0));
EXPECT_EQ (25.4, square-root (645.16));
EXPECT_EQ (50.3321, square-root (2533.310224));
}
注意,如果禁用了任何測試,Google 框架會在測試執行結束時輸出警告消息,見 清單 7。
清單 7. Google 警告用戶在框架中有禁用的測試
1 FAILED TEST
YOU HAVE 1 DISABLED TEST
如果希望繼續運行禁用的測試,那么在命令行上傳遞 -gtest_also_run_disabled_tests 選項。清單 8 給出運行 DISABLE_PositiveNos 測試時的輸出。
清單 8. Google 允許運行已經禁用的測試
[----------] 1 test from DISABLED_SquareRootTest
[ RUN ] DISABLED_SquareRootTest.PositiveNos
..\user_sqrt.cpp(6854): error: Value of: square-root (2533.310224)
Actual: 50.332
Expected: 50.3321
[ FAILED ] DISABLED_SquareRootTest.PositiveNos (2 ms)
[----------] 1 test from DISABLED_SquareRootTest (2 ms total)
[ FAILED ] 1 tests, listed below:
[ FAILED ] SquareRootTest. PositiveNos
斷言
Google 測試框架提供一整套預定義的斷言。斷言分為兩類 — 名稱以 ASSERT_ 開頭的斷言和名稱以 EXPECT_ 開頭的斷言。如果一個斷言失敗,ASSERT_* 斷言會終止程序執行,而 EXPECT_* 斷言繼續運行。當斷言失敗時,這兩者都輸出文件名、行號和可定制的消息。比較簡單的斷言包括 ASSERT_TRUE (condition) 和 ASSERT_NE (val1, val2)。前者期望條件總是成立,而后者期望兩個值不匹配。這些斷言也適用于用戶定義的類型,但是必須覆蓋相應的比較操作符(==、!=、<= 等等)。
浮點數比較
Google 提供 清單 9 所示的宏以支持浮點數比較。
清單 9. 用于浮點數比較的宏
ASSERT_FLOAT_EQ (expected, actual)
ASSERT_DOUBLE_EQ (expected, actual)
ASSERT_NEAR (expected, actual, absolute_range)
EXPECT_FLOAT_EQ (expected, actual)
EXPECT_DOUBLE_EQ (expected, actual)
EXPECT_NEAR (expected, actual, absolute_range)
為什么需要用單獨的宏進行浮點數比較?使用 ASSERT_EQ 不行嗎?使用 ASSERT_EQ 和相關的宏可能可以,也可能不行,但是使用專門用于浮點數比較的宏更好。通常,不同的中央處理單元 (CPU) 和操作環境以不同的方式存儲浮點數,簡單地比較期望值和實際值是無效的。例如,ASSERT_FLOAT_EQ (2.00001, 2.000011) 會順利通過 — 如果直到小數點后四位都匹配,Google 就不會拋出錯誤。如果需要更精確的比較,應該使用 ASSERT_NEAR (2.00001, 2.000011, 0.0000001),就會得到 清單 10 所示的錯誤。
清單 10. ASSERT_NEAR 產生的錯誤消息
Math.cc(68): error: The difference between 2.00001 and 2.000011 is 1e-006, which exceeds
0.0000001, where
2.00001 evaluates to 2.00001,
2.000011 evaluates to 2.00001, and
0.0000001 evaluates to 1e-007.
死亡測試
Google C++ Testing Framework 有一類有趣的斷言(ASSERT_DEATH、ASSERT_EXIT 等),它們稱為死亡斷言。使用這種斷言檢查在例程的輸入錯誤的情況下是否發出正確的錯誤消息,或者例程是否退出并返回正確的退出碼。例如,在 清單 3 中,當執行 square-root (-22.0) 時應該產生錯誤消息,程序退出,返回狀態應該是 -1 而不是 -1.0。清單 11 使用 ASSERT_EXIT 檢查是否是這樣。
清單 11. 使用 Google 框架運行死亡測試
#include "gtest/gtest.h"
double square-root (double num) {
if (num < 0.0) {
std::cerr << "Error: Negative Input\n";
exit(-1);
}
// Code for 0 and +ve numbers follow…
}
TEST (SquareRootTest, ZeroAndNegativeNos) {
ASSERT_EQ (0.0, square-root (0.0));
ASSERT_EXIT (square-root (-22.0), ::testing::ExitedWithCode(-1), "Error:
Negative Input");
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
ASSERT_EXIT 檢查函數是否退出并返回正確的退出碼(即 exit 或 _exit 例程的參數),對引號中的字符串和函數發送到標準錯誤的字符串進行比較。注意,錯誤消息必須發送到 std::cerr 而不是 std::cout。清單 12 給出 ASSERT_DEATH 和 ASSERT_EXIT 的原型。
清單 12. 死亡斷言的原型
ASSERT_DEATH(statement, expected_message)
ASSERT_EXIT(statement, predicate, expected_message)
Google 提供預定義的謂詞 ::testing::ExitedWithCode(exit_code)。只有在程序退出且退出碼與謂詞中的 exit_code 相同的情況下,這個謂詞的結果才是 true。ASSERT_DEATH 比 ASSERT_EXIT 簡單;它只檢查標準錯誤中的錯誤消息是否是用戶期望的消息。
理解測試裝備
在執行單元測試之前,通常要執行一些定制的初始化。例如,如果希望度量測試的時間/內存占用量,就需要放置一些測試專用代碼以度量這些值。這就是裝備的用途 — 它們幫助完成這種定制的測試初始化。清單 13 給出一個裝備類的示例。
清單 13. 測試裝備類
class myTestFixture1: public ::testing::test {
public:
myTestFixture1( ) {
// initialization code here
}
void SetUp( ) {
// code here will execute just before the test ensues
}
void TearDown( ) {
// code here will be called just after the test completes
// ok to through exceptions from here if need be
}
~myTestFixture1( ) {
// cleanup any pending stuff, but no exceptions allowed
}
// put in any custom data members that you need
};
這個裝備類派生自 gtest.h 中聲明的 ::testing::test 類。清單 14 是使用這個裝備類的示例。注意,它使用 TEST_F 宏而不是 TEST。
清單 14. 裝備的使用示例
TEST_F (myTestFixture1, UnitTest1) {
….
}
TEST_F (myTestFixture1, UnitTest2) {
….
}
在使用裝備時,要注意以下幾點:
可以在構造函數或 SetUp 方法中執行初始化或分配資源。由用戶選擇具體方式。
可以在 TearDown 或析構函數例程中釋放資源。但是,如果需要異常處理,那么只能在 TearDown 代碼中進行,因為從析構函數中拋出異常會導致不確定的結果。
在以后的版本中,Google 斷言宏可能會在平臺上拋出異常。因此,為了便于維護,最好在 TearDown 代碼中使用斷言宏。
并不跨多個測試使用同一個測試裝備。對于每個新的單元測試,框架創建一個新的測試裝備。在 清單 14 中,由于要創建兩個 myFixture1 對象,所以兩次調用 SetUp 例程(請注意使用正確的拼寫)。
結束語
本文僅僅觸及了 Google C++ Testing Framework 的皮毛。可以從 Google 網站獲得關于這個框架的詳細信息。對于高級開發人員,我建議閱讀 Boost 單元測試框架和 CppUnit 等開放回歸框架方面的其他文章。更多信息參見 參考資料。
關于作者
Arpan Sen 是致力于電子設計自動化行業的軟件開發首席工程師。他使用各種 UNIX 版本(包括 Solaris、SunOS、HP-UX、IRIX,以及 Linux 和 Microsoft Windows)已經多年。他熱衷于各種軟件性能優化技術、圖論和并行計算。Arpan 獲得了軟件系統碩士學位。